Reputation: 8556
I have an enum
:
public enum Fruits
{
Apple = 14,
Lemon = 174,
Grapes = 200,
Peach = 1
}
and a list by this enum
:
IEnumerable<Fruits> Fruits = new List<Fruits>();
By default when I call getValues
on the enum
it sorts the entries by their id.
I show the list as a dropdown in the UI and want to sort the members of the list in specific order. In my sample I want Lemon
to be the first item in the list.
I tried to order the items by the Lemon entry with something like this:
Fruits.OrderBy(f => f.Lemon);
but I am not allowed to do this f.Lemon
in this context. Maybe I can foreach
the list remove the Lemon item and then insert it as a first entry.
I am quite new to programming and I have found some similar questions but not with enum
type.
Upvotes: 1
Views: 1494
Reputation: 460360
You can use OrderByDescending
+ ThenBy
:
fruits.OrderByDescending(f => f == Fruits.Lemon)
.ThenBy(f => f);
Note that the variable should have a different name than the enum type (I've used lowercase fruits
).
If you want to order second by the name:
.ThenBy(f => f.ToString());
f == Fruits.Lemon
returns a bool which you can order by. It's similar to SQL CASE
:
ORDER BY CASE WHEN Fruit = 'Lemon' THEN 1 ELSE 0 END DESC, FRUIT ASC
Upvotes: 4