I create a dropdownlist from Enum.
public enum Level
{
Beginner = 1,
Intermediate = 2,
Expert = 3
}
here's my extension.
public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
{
IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
var result = from TEnum e in values
select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };
var tempValue = new { ID = 0, Name = "-- Select --" };
return new SelectList(result, "Id", "Name", enumObj);
}
the problem I have is to insert antoher item into IEnumerable. I just could not figure out how to do it. Can someone please modify my code to insert "--select--" to the top.
You can't modify a IEnumerable<T>
object, it only provides an interface to enumerate elements. But you could use .ToList()
to convert the IEnumerable<T>
to a List<T>
.
I'm not sure if this is what you want:
public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
{
IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
var result = from TEnum e in values
select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };
var tempValue = new { ID = 0, Name = "-- Select --" };
var list = result.ToList(); // Create mutable list
list.Insert(0, tempValue); // Add at beginning of list
return new SelectList(list, "Id", "Name", enumObj);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With