KD82 KD82 - 3 months ago 18
JSON Question

'Newtonsoft.Json.Linq.JArray' does not contain a definition for

I have the following JSON:

{
"ok": true,
"resp": [
{
"aaa": 111,
"bbb": "xyz",
"ccc": [
{...},
{
"ddd": "hello",
"eee": 666,
},
{...}
],
"read": false
},
{...},
{...}
]
}


and this C# code:

dynamic my_obj = JsonConvert.DeserializeObject(JSON);
var resps = my_obj.resp;
var x = ((IEnumerable<dynamic>)resps).Cast<dynamic>()
.Where(p => p.ccc.eee == 666).Count();


and below error:

'Newtonsoft.Json.Linq.JArray' does not contain a definition for 'eee'.


I know, I could iterate through all elements in 'resps' and count elements, where element 'ccc.eee' equals 666, but is it possible to do it in one line with linq?

Answer

Since ccc is array, you need to iterate over it.

Count number of eee=666:

int x = ((IEnumerable<dynamic>)resps).Sum(
            p => ((IEnumerable<dynamic>)p.ccc).Count(o => o.eee == 666));

Count number of objects in resp having at least one eee=666:

int x = ((IEnumerable<dynamic>)resps).Count(
            p => ((IEnumerable<dynamic>)p.ccc).Any(o => o.eee == 666));
Comments