例如,可以通过 col2 对 JArray 进行排序吗?
[
{
"col1": "thiscol",
"col2": "thisval"
},
{
"col1": "thiscol2",
"col2": "thisval2"
},
{
"col1": "thiscol3",
"col2": "thisval3"
}
]
如果将其转换为数组是唯一的解决方案,那么我该怎么办呢?
答案 0 :(得分:20)
我认为您不能对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"
}
]