0

I am reading some JSON and converting it to a dynamic list. Below is My Code:

dynamic data = JObject.Parse(response);
var result = data.result;
var result = ((IEnumerable)arr).Cast<dynamic>().ToList();

var id = result[0].id;
var filtereddata = result.Where("id==1");

The line

var filtereddata = result.Where("id==1");

Gives error No property or field 'id' exists in type 'Object while var id = result[0].id; seems to be working.

The JSON I am parsing is :

{
"count": 1,
"result": [
{
  "id": 11,
  "name": "Locations",

}]
}

Please let me know if more information is needed. Thanks for your valuable time.

Edit: Even tried var filtereddata = result.Where(c=>c.id==1).Select("id"); using lambda expression but still the same issue.

8
  • 1
    I don't think Dynamic LINQ works with dynamic types. Commented Oct 5, 2016 at 9:44
  • Why dynamic? Why not poco? json2csharp.com Commented Oct 5, 2016 at 9:51
  • I cannot use poco and exacts fields can vary. So have to use dynamic. If there is any solution other then Dynamic Linq I can check that as well Commented Oct 5, 2016 at 9:53
  • How about regular LINQ? e.g. Where(x => x.id == 1). Commented Oct 5, 2016 at 10:28
  • Actually I have the where condition as a string "id==1". So that is why I was using the Dynamic Linq Commented Oct 5, 2016 at 10:51

1 Answer 1

3

Dynamic LINQ does not work with dynamic type. LINQ to Objects would work, but since you are receiving the filter as string, it's not applicable.

The workaround is to use temporary anonymous projection before applying the dynamic Where and then selecting back the original object:

var filtereddata = result
    .Select(x => new { item = x, id = (int)x.id, name = (string)x.name })
    .Where("id==1")
    .Select(x => x.item);
Sign up to request clarification or add additional context in comments.

2 Comments

If anonymous projection to a well defined is feasible, then why create IEnumerable<dynamic> in first place, can directly create a schema post Json read
@MrinalKamboj I have no idea why OP has chosen to parse into JObject which internally creates dynamic JArray / JObject / JProperty. The answer is just covering the concrete use case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.