在 JArray 中使用 LINQ

Ива*_*йко 5 c# linq json json.net

我有一个 JSON

{
  "departments": [
    {
      "2": {"city": "Petersburg", "employees": "1200"}
    },
    {
      "1": {"city": "Ekaterinburg", "employees": "4000"}
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

如果我知道使用 LINQ 或其他东西的 ID,我如何获得城市的价值?

我试过

var id = 2;
json["departments"].Single(x=>x.Name==id.ToString())["city"];
Run Code Online (Sandbox Code Playgroud)

但它不起作用,我收到一个编译错误:

{
  "departments": [
    {
      "2": {"city": "Petersburg", "employees": "1200"}
    },
    {
      "1": {"city": "Ekaterinburg", "employees": "4000"}
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

演示小提琴在这里

dbc*_*dbc 5

您的 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.
Run Code Online (Sandbox Code Playgroud)

或者,等效地:

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();
Run Code Online (Sandbox Code Playgroud)

或者,您可以SelectToken()为此目的使用:

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

SelectToken()支持JSONPath 语法,并且[*]是 JSONPath 通配符运算符,指示应搜索所有数组项。

演示小提琴在这里