user2580179
user2580179

Reputation: 259

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

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

Upvotes: 1

Views: 98

Answers (2)

jason.kaisersmith
jason.kaisersmith

Reputation: 9610

You can "force" a specific order by numbering your enum such as this

public enum Number
{
    One = 1,
    Two = 2,
    Three = 3,
    Four = 4,
    Five = 5
}

Then when you sort it will be in the order you specified.

(Strange that for me the list appeared in the right order without needing this!)

Upvotes: 0

vhr
vhr

Reputation: 1664

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();

Upvotes: 3

Related Questions