是否可以按col2对JArray进行排序?
[
{
"col1": "thiscol",
"col2": "thisval"
},
{
"col1": "thiscol2",
"col2": "thisval2"
},
{
"col1": "thiscol3",
"col2": "thisval3"
}
]
如果将其转换为数组是唯一的解决方案,那么我怎么能做到这一点?
我不认为可以对JArray进行排序,但是可以对内容进行排序并将结果加载到另一个JArray中。这对你有用吗?
string json = @"
[
{
""col1"": ""foo"",
""col2"": ""bar""
},
{
""col1"": ""baz"",
""col2"": ""quux""
},
{
""col1"": ""fizz"",
""col2"": ""bang""
}
]";
JArray array = JArray.Parse(json);
JArray sorted = new JArray(array.OrderBy(obj => (string)obj["col2"]));
Console.WriteLine(sorted.ToString(Formatting.Indented));
输出:[
{
"col1": "fizz",
"col2": "bang"
},
{
"col1": "foo",
"col2": "bar"
},
{
"col1": "baz",
"col2": "quux"
}
]
小提琴:https://dotnetfiddle.net/2lTZP7