使用LINQ查询语句可以遍历JObject对象,而不使用foreach循环。下面是一个示例代码:
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
string json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JObject jObject = JObject.Parse(json);
var properties = jObject.Properties()
.Select(p => new { Key = p.Name, Value = p.Value });
foreach (var property in properties)
{
Console.WriteLine(property.Key + ": " + property.Value);
}
}
}
在上面的代码中,我们首先使用JObject.Parse()
方法将一个JSON字符串解析为JObject对象。然后,我们使用LINQ的Properties()
方法获取JObject对象的属性集合。接下来,我们使用Select()
方法将每个属性转换为包含键值对的匿名对象。最后,我们通过foreach循环遍历这些属性并输出它们的键和值。
运行上述代码将输出:
name: John
age: 30
city: New York
这样就完成了对JObject对象的遍历,而不使用foreach循环。