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.
You can use
OrderByDescending+ThenBy: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:
f == Fruits.Lemonreturns a bool which you can order by. It’s similar to SQLCASE: