.NET Core C#中如何通过属性值查询System.Text.Json.Nodes.JsonArray
在.NET Core中查询System.Text.Json.Nodes.JsonArray的内置方法方案
核心结论
JsonArray 实现了 IEnumerable<JsonNode?> 接口,因此可以直接使用LINQ扩展方法(无需手动编写foreach/for循环,也不需要第三方库)来筛选符合条件的JsonObject或获取其索引。
具体实现示例
1. 查询符合条件的JsonObject并转为JsonArray
针对查询条件"value" == "OCBC",可以通过Where过滤结果,再构造新的JsonArray:
using System.Linq; using System.Text.Json.Nodes; // 你的原始JsonArray JsonArray arr= (JsonArray)JsonObject.Parse("[ \r\n{\"key\": 1,\"value\": \"UOB\" ,\"connections\":[\"WebPOS_dropdownlist\",\"WebIMS_dropdownlist\"] ,\"synced\":0,\"last_synced\":\"2024/7/16 4:26:34\"}, \r\n{\"key\": 2,\"value\": \"OCBC\",\"connections\":[],\"synced\":1,\"last_synced\":\"2024/7/16 4:26:34\" }\r\n]"); // 过滤出所有value为OCBC的JsonObject var matchedObjects = arr.Where(node => node is JsonObject obj && obj["value"]?.GetValue<string>() == "OCBC" ).Cast<JsonObject>(); // 将结果转为JsonArray JsonArray filteredArray = new JsonArray(matchedObjects);
2. 查询匹配项的数组索引
通过Select结合索引参数,筛选出符合条件的元素索引:
// 获取所有匹配项的索引 var matchedIndices = arr.Select((node, index) => new { Node = node, Index = index }) .Where(item => item.Node is JsonObject obj && obj["value"]?.GetValue<string>() == "OCBC" ) .Select(item => item.Index); // 获取第一个匹配的索引(不存在则返回默认值0,可根据需求处理) int? firstMatchedIndex = matchedIndices.FirstOrDefault();
注意事项
- 需引入
System.Linq命名空间,才能使用LINQ扩展方法。 - 使用
obj["value"]?.GetValue<string>()是为了避免空引用异常(当节点不存在或类型不匹配时返回null)。
内容的提问来源于stack exchange,提问作者民麒張
相关产品推荐
相关产品推荐

