Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在JArray中使用LINQ_C#_Json_Linq_Json.net - Fatal编程技术网

C# 在JArray中使用LINQ

C# 在JArray中使用LINQ,c#,json,linq,json.net,C#,Json,Linq,Json.net,我有一个JSON { "departments": [ { "2": {"city": "Petersburg", "employees": "1200"} }, { "1": {"city": "Ekaterinburg", "employees"

我有一个JSON

{
  "departments": [
    {
      "2": {"city": "Petersburg", "employees": "1200"}
    },
    {
      "1": {"city": "Ekaterinburg", "employees": "4000"}
    }
  ]
}
如果我知道一个使用LINQ或其他东西的ID,如何获得城市的价值

我试过了

var id = 2;
json["departments"].Single(x=>x.Name==id.ToString())["city"];
但它不起作用,我得到一个编译错误:

“JToken”不包含“Name”的定义,并且找不到接受“JToken”类型的第一个参数的可访问扩展方法“Name”(是否缺少using指令或程序集引用?)

演示小提琴。

您的LINQ查询可以按如下方式实现:

var id = "2";
var city = (string)json["departments"]
    .Where(o => o[id] != null) // From the departments array, select the object where the required id property exists
    .Select(o => o[id]["city"]).SingleOrDefault(); // An extract the value of "city" from the nested object.
或者,相当于:

var id = "2";
var city = (string)json["departments"]
    .SelectMany(i => i) // Use SelectMany() to project the properties of the array items to a flat enumerable 
    .Cast<JProperty>()  // Cast them to JProperty
    .Where(p => p.Name == id) // Now you can use Name
    .Select(p => p.Value["city"])
    .SingleOrDefault();
SelectToken()
支持,而
[*]
是JSONPath通配符运算符,指示应搜索所有数组项

演示小提琴

var id = "2";
var path = $"departments[*].{id}.city"; // departments[*].2.city
var city = (string)json.SelectToken(path);