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.

Anshuman Jasrotia
  • 3,135
  • 8
  • 48
  • 81

1 Answers1

2

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);
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • If anonymous projection to a well defined is feasible, then why create `IEnumerable` in first place, can directly create a schema post Json read – Mrinal Kamboj Oct 05 '16 at 12:09
  • 1
    @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. – Ivan Stoev Oct 05 '16 at 12:13