Order list by special enum value in linq

Viewed 6201

i want to order my list according to below picture (first field is int and second is an Enum)

i want to records with "foo" value comes at first of output

how can i do this in c# and linq?

thanks in advance

public enum myEnum{
    goo,
    foo,
    boo
}

enter image description here

4 Answers

A simpler approach is to just evaluate the enum and return comparison value:

 var result = list.OrderBy(item => item.myEnum == myEnum.foo ? 1 : 2)
                  .ThenBy(item => item.myEnum == myEnum.boo ? 1 : 2)
                  .ThenBy(item => item.myEnum == myEnum.goo ? 1 : 2); 

This way you won't need extra variables and a more readable code.

Sample: https://repl.it/repls/CornsilkGiganticDevelopers

I found this reasonably simple as well:

var result = list.OrderBy(item => item.myEnum == myEnum.foo)
              .ThenBy(item => item.myEnum == myEnum.boo)
              .ThenBy(item => item.myEnum == myEnum.goo); 
Related