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?
A:
Now I used Tuple<string, string>
but you can convert this to use anything:
var values = Enum.GetValues(typeof(DayOfWeek))
.Cast<DayOfWeek>()
.Select(d => Tuple.Create(((int)d).ToString(), d.ToString()))
.ToList()
ChaosPandion
2010-08-15 22:04:50
+1
A:
You can use Enum.GetNames()
to get a string array containing the names of the enum items. If your item names are user friendly, then this is probably good enough. Otherwise, you could create your own GetName()
method that would return a nice name for each item.
OR - if the enum will never (or rarely) change, you could just create a method that directly adds hard-coded items to your dropdown. This is probably more efficient (if that is important to you).
Ray
2010-08-15 22:05:20
+6
A:
You can use LINQ:
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem {
Text = v.ToString(),
Value = ((int)v).ToString()
});
SLaks
2010-08-15 22:05:30
Although *LINQ* has become the unofficial name of the Enumerable Extensions I can't help but wonder if something more appropriate exists.
ChaosPandion
2010-08-15 22:10:48
It's part of the Linq namespace and project, and IMO the correct name. Linq is just also the name for the language extension.
Dykam
2010-08-15 22:18:22
@SLaks - this code above is not compiling. i am trying to do this: List<SelectListItem> dropdown = Enum.GetValues(typeof(EventType)).Select(v => new SelectListItem { Selected = (int)v == id, Text = v.ToString(), Value = ((int)v).ToString() }).ToList(); return dropdown;but getting an error: "Cannot cast expression from TSource to int" in the lines that are doing (int)v)
ooo
2010-08-15 22:37:38
@ooo: Try @ChaosPandion's edit.
SLaks
2010-08-15 23:07:03
You could say: "You can use System.Linq"
jfar
2010-08-16 01:37:42