Using Linq.Dynamic where method with a dynamic list gives error

c# dynamic dynamic-linq linq

Question

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.

1
0
10/5/2016 12:02:13 PM

Accepted Answer

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);
2
10/5/2016 12:06:08 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow