【问题标题】:Linq to json filtering results with Where clause使用 Where 子句的 Linq to json 过滤结果
【发布时间】:2015-08-25 07:03:01
【问题描述】:

我是 json 新手。我正在尝试使用 C# 中的 linq to json 查询过滤 json 数据。 我正在尝试从 json 数据中检索多个值:

string json= @"{
 "parts": [
    {

      "attributes": {
        "Motherboard": "Gigabyte GA-H81M-S2H",
        "Max RAM": "16GB",
        "Form Factor": "Micro ATX",
        "RAM Slots": 2,
        "Socket / CPU": "LGA1150"
      },
      "type": "Motherboard",
      "name": "Gigabyte GA-H81M-S2H",
      "slug": "gigabyte-motherboard-gah81ms2h"
    },
    {
        "attributes": {
        "Motherboard": "MSI H55-G43",
        "Max RAM": "16GB",
        "Form Factor": "ATX",
        "RAM Slots": 4,
        "Socket / CPU": "LGA1156"
      },
      "type": "Motherboard",
      "name": "MSI H55-G43",
      "slug": "msi-motherboard-h55g43"
    },
    {
      "url": "http://pcpartpicker.com/part/asus-motherboard-rampageivblackedition",
      "attributes": {
        "Motherboard": "Asus Rampage IV Black Edition",
        "Max RAM": "128GB",
        "Form Factor": "EATX",
        "RAM Slots": 8,
        "Socket / CPU": "LGA2011"
      },
      "type": "Motherboard",
      "name": "Asus Rampage IV Black Edition",
      "slug": "asus-motherboard-rampageivblackedition"
    }
 ],

}";

这是我的 C# 代码:

JObject results = JObject.Parse(json);
  var categories = from c in results["parts"]["attributes"].Children()["Motherboard"].Values<string>()
                         group c by c
                         into g
                         orderby g.Count() descending
                         select new { Category = g.Key, Count = g.Count() };

我尝试使用此代码,但它没有返回任何结果。请让我知道我在哪里做错了,或者这是编写查询的正确方法。谁能帮我解决这个问题。

【问题讨论】:

    标签: c# json linq-to-json


    【解决方案1】:

    您可以使用SelectTokens 进行此类查询。它支持JSONPath 查询语法。因此:

            var categories = from c in results.SelectTokens("parts[*].attributes.Motherboard")
                             group c by c
                                 into g
                                 orderby g.Count() descending
                                 select new { Category = (string)g.Key, Count = g.Count() };
    

    在您的 JSON 中,"parts" : [...] 的值是一个数组;在查询中,"parts[*]" 是一个通配符,用于搜索数组的所有元素。

    【讨论】:

    • 感谢您的回复。它正在工作,如何选择多个对象
    • @Rajesh - 你的评论没有足够的细节让我确定如何回答,所以你可能想问另一个问题。 stackoverflow 上的首选格式是one question per question
    • 对不起,如果我想选择名称,请从我的 json 数据中输入如何传入选择令牌
    • 您能否提供更多帮助,以提供 linq to json 教程的链接
    猜你喜欢
    • 1970-01-01
    • 2015-04-10
    • 2023-03-11
    • 2022-08-06
    • 2023-03-08
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多