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
}
This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With