Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order list by special enum value in linq

Tags:

c#

enums

linq

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

like image 865
Ali7091 Avatar asked Jul 11 '17 13:07

Ali7091


People also ask

Is LINQ orderby stable?

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved.

What are enum types?

Enumerated (enum) types are data types that comprise a static, ordered set of values. They are equivalent to the enum types supported in a number of programming languages. An example of an enum type might be the days of the week, or a set of status values for a piece of data.

Are enums slow in Python?

It's kind of slow. We were using enums a lot in our code, until we noticed that enum overhead takes up single digit percentages of our CPU time! Luckily, it only took a few hours to write a much faster implementation with almost the same functionality.


1 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

like image 150
jbalintac Avatar answered Oct 19 '22 17:10

jbalintac