gpt4 book ai didi

c# - 在 JArray 中使用 LINQ

转载 作者:行者123 更新时间:2023-12-03 16:31:28 27 4
gpt4 key购买 nike

我有一个 JSON

{
"departments": [
{
"2": {"city": "Petersburg", "employees": "1200"}
},
{
"1": {"city": "Ekaterinburg", "employees": "4000"}
}
]
}
如果我知道使用 LINQ 或其他东西的 ID,我如何获得城市的值(value)?
我试过
var id = 2;
json["departments"].Single(x=>x.Name==id.ToString())["city"];
但它不起作用,我收到一个编译错误:
'JToken' does not contain a definition for 'Name' and no accessible extension method 'Name' accepting a first argument of type 'JToken' could be found (are you missing a using directive or an assembly reference?)

演示 fiddle here .

最佳答案

您的 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() 以此目的:
var id = "2";
var path = $"departments[*].{id}.city"; // departments[*].2.city
var city = (string)json.SelectToken(path);
SelectToken()支持 JSONPath syntax , 和 [*]是 JSONPath 通配符运算符,指示应搜索所有数组项。
演示 fiddle here .

关于c# - 在 JArray 中使用 LINQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66446158/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com