Would it be possible to sort the JArray below by col2 for example?
[
{
"col1": "thiscol",
"col2": "thisval"
},
{
"col1": "thiscol2",
"col2": "thisval2"
},
{
"col1": "thiscol3",
"col2": "thisval3"
}
]
If converting this to an Array is the only solution then how could I do this?
I don't think you can sort a JArray in place, but you can sort the contents and load the result into another JArray. Would this work for you?
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));
Output:
[
{
"col1": "fizz",
"col2": "bang"
},
{
"col1": "foo",
"col2": "bar"
},
{
"col1": "baz",
"col2": "quux"
}
]
Fiddle: https://dotnetfiddle.net/2lTZP7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With