【问题标题】:Extract a JSON property using LINQ使用 LINQ 提取 JSON 属性
【发布时间】:2020-01-16 17:09:12
【问题描述】:

我有一个json对象如下:

{
    "search-results": {
        "results-count": "2"
        "entry": [
            {
                "id": "0",
                "count": "10",
            },
            {
                "id": "1",
                "count": "22",
            }
        ]
    }
}

我想得到counts 的总和; 32 在这个例子中。我正在考虑使用 LINQ 执行此操作,但任何更“可读”的替代方案将不胜感激。

【问题讨论】:

  • 就像一个简单的 linq 查询,如 searchresults.entry.Sum(i => i.count); ?
  • 无法获得类似的工作,任何代码示例?
  • 到目前为止你尝试过什么?请将您的 LINQ 也添加到问题中。

标签: c# json linq .net-core


【解决方案1】:

试试这个:

var json = @"{
        'search-results': {
                    'results-count': '2',
                    'entry': [
                    {
                        'id': 0,
                        'count': 10,
                    },
                    {
                        'id': 1,
                        'count': 22,
                    }
            ]
        }
    }";


JObject searchResult = JObject.Parse(json);
int sum = (from entry in searchResult["search-results"]["entry"]
            select (int)entry["count"]).Sum();

【讨论】:

    【解决方案2】:

    你可以用 Linq 做到这一点。例如,

    var jobject = JObject.Parse(jsonString);
    var result = jobject["search-results"]["entry"].Sum(x=>Convert.ToInt32(x["count"]));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多