How to sort the list object based on Enum order using linq

Advertisements

I want to sort the list based on enum name / value using linq c# 6.0

My enum would look like this

public enum Number
{
    One,
    Two,
    Three,
    Four,
    Five            
}

My list without sorting

[
{
"a":ddd
"b":aaa
"w":"Four"
},
{
"a":sss
"b":fff
"w":"Two"
},
{
"a":bbbb
"b":zzzz
"w":"Three"
},
{
"a":hhh
"b":kkk
"w":"Five"
},{
"a":llll
"b"oooo
"w":"One"
},
]

I want to sort above list by mapping property "W" with enum order, the output would be

 [
{
"a":llll
"b"oooo
"w":"One"
},
{
"a":sss
"b":fff
"w":"Two"
}
....
]

Tried following but no luck

var a = myList.OrderBy(x => x.W).ToList();

>Solution :

Try this:

// you need to convert your 'w' string to enum first, then sort
var a = myList.OrderBy(x => Enum.Parse((typeof(Number),x.W)).ToList();

Leave a ReplyCancel reply