& # 39; Newtonsoft.Json.Linq.JArray& # 39;不包含的定义

本文关键字:包含 定义 Json Newtonsoft Linq JArray | 更新日期: 2023-09-27 18:03:44

我有以下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在一行中完成呢?

& # 39; Newtonsoft.Json.Linq.JArray& # 39;不包含的定义

由于ccc是数组,因此需要对其进行迭代。

Count number of eee=666:

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

计算至少有一个eee=666的对象个数:

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