I'm populating a DropDownList
in MVC 4 from an enum
and I want to order the enum values from largest to smallest. However, there doesn't seem to be a direct way of approaching this. Currently, I'm using this code to add to a dictionary with the key being the ID and the value being the display text:
var priorities = Enum.GetValues(typeof(Models.Priority)).OfType<Models.Priority>().ToList();
for (int i = priorities.Count - 1; i >= 0; i--)
{
Models.Priority priority = priorities[i];
prioritiesDictionary.Add((int)priority, "Priority " + ((int)priority).ToString());
}
I don't believe that putting enum values into a list and looping backwards is the most efficient method. There are only four values in the enum, but is there a better way to perform an OrderBy
operation on what is returned from Enum.GetValues
? I know it might be minimal performance impact doing it the way I am, but I want to know for larger enums.
Sounds like you just want:
var priorities = ((Models.Priority[]) Enum.GetValues(typeof(Models.Priority)))
.OrderByDescending(x => x);
Or to avoid quite as many brackets:
var priorities = (Models.Priority[]) Enum.GetValues(typeof(Models.Priority));
var ordered = priorities.OrderByDescending(x => x);
It's not clear how your current code is helping you, by giving you a dictionary - but the above will definitely give you a sequence of enum values, ordered from highest to lowest. You don't need to cast to int
, because enum values of the same type are already comparable to each other.
If you need a list, just call ToList()
after the OrderByDescending
call.
See more on this question at Stackoverflow