sagar43 sagar43 - 3 months ago 6
C# Question

Parse Json string and sort based on property in C#

I am working on a window app in which a json string like

{
"0":{"UID":"3182713a-60de-4576-ad82-6804d2acf2b7","Rating":-1},
"1":{"UID":"eb41478e-e9bc-428e-8203-482f6a329666","Rating":-13},
"2":{"UID":"a0922817-e706-4478-8995-d258bada488d","Rating":6.0033992049},
"3":{"UID":"e0716752-56f4-49af-a811-ae55c69baa3d","Rating":-4.9836395671},
"4":{"UID":"ec6bf376-17b5-4a9e-92be-990557551cd0","Rating":-7.754526396}
}


I want to parse and sort it by rating. Please suggest how i can achieve it.

Answer

You will need to deseralise the JSON into a Dictionary<int, YourClass>

Example:

var json = @"{
""0"":{""UID"":""3182713a-60de-4576-ad82-6804d2acf2b7"",""Rating"":-1},
""1"":{""UID"":""eb41478e-e9bc-428e-8203-482f6a329666"",""Rating"":-13},
""2"":{""UID"":""a0922817-e706-4478-8995-d258bada488d"",""Rating"":6.0033992049},
""3"":{""UID"":""e0716752-56f4-49af-a811-ae55c69baa3d"",""Rating"":-4.9836395671},
""4"":{""UID"":""ec6bf376-17b5-4a9e-92be-990557551cd0"",""Rating"":-7.754526396}
}";


var result = JsonConvert.DeserializeObject<Dictionary<int,MyCustomClass>>(json);

MyCustomClass

public class MyCustomClass
{
    public Guid UID {get;set;}
    public decimal Rating {get;set;}
}

In the Dictionary<int, MyCustomClass> the int is the numeric key in your Json.

Note: I am using Newtonsoft Json here.

Once you have done the above you can sort it like the following using LINQ:

var sorted = result.OrderBy(x => x.Value.Rating);
// OR
var sorted = result.OrderByDescending(x => x.Value.Rating);