'Newtonsoft.Json.Linq.JArray'不包含。的定义

时间:2016-08-23 20:33:57

标签: c# json linq

我有以下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在一行中进行吗?

1 个答案:

答案 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));
相关问题