Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
{
"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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading