How can I convert an enumeration into a List<SelectListItem>?

leora picture leora · Aug 15, 2010 · Viewed 47.3k times · Source

i have an asp.net-mvc webpage and i want to show a dropdown list that is based off an enum. I want to show the text of each enum item and the id being the int value that the enum is associated with. Is there any elegant way of doing this conversion?

Answer

SLaks picture SLaks · Aug 16, 2010

You can use LINQ:

Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem {
    Text = v.ToString(),
    Value = ((int)v).ToString()
}).ToList();