我有以下JSON:
{
"ok": true,
"resp": [
{
"aaa": 111,
"bbb": "xyz",
"ccc": [
{...},
{
"ddd": "hello",
"eee": 666,
},
{...}
],
"read": false
},
{...},
{...}
]
}
和这个C#代码:
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();
以下错误:
'Newtonsoft.Json.Linq.JArray' does not contain a definition for 'eee'.
我知道,我可以遍历'resps'中的所有元素并计算元素,其中元素'ccc.eee'等于666,但是可以用linq在一行中进行吗?
答案 0 :(得分:6)
由于ccc
是数组,因此需要迭代它。
eee = 666的计数:
int x = ((IEnumerable<dynamic>)resps).Sum(
p => ((IEnumerable<dynamic>)p.ccc).Count(o => o.eee == 666));
计算resp中具有至少一个eee = 666的对象数:
int x = ((IEnumerable<dynamic>)resps).Count(
p => ((IEnumerable<dynamic>)p.ccc).Any(o => o.eee == 666));