简体   繁体   English

Linq到带有where子句的json过滤结果

[英]Linq to json filtering results with Where clause

I'm new to json. 我是json的新手。 I'm trying to filter json data using linq to json query in C#. 我正在尝试使用linq过滤json数据到C#中的json查询。 I'm trying to retrieve multiple values from json data: 我正在尝试从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"
    }
 ],

}";

This is my C# code: 这是我的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() };

I tried with this code and it not returns any result.Please let me know where I'm doing mistake or is this the proper way to write the query.Can anyone please help me to solve this. 我尝试使用此代码,但未返回任何结果。请让我知道我在哪里做错了,或者这是编写查询的正确方法。任何人都可以帮助我解决这个问题。

You can use SelectTokens for queries of this nature. 您可以将SelectTokens用于这种性质的查询。 It supports JSONPath query syntax. 它支持JSONPath查询语法。 Thus: 从而:

        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() };

In your JSON, the value of "parts" : [...] is an array; 在您的JSON中, "parts" : [...]的值"parts" : [...]是一个数组; in the query, "parts[*]" is a wildcard that searches through all elements of the array. 在查询中, "parts[*]"是通配符,用于搜索数组的所有元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM