I'm trying to convert an enum to a List as mentioned in this example e.g.
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem {
Text = v.ToString(),
Value = ((int)v).ToString()
}).ToList();
This work but I want to amend it to work with a generic enum
public static List<SelectListItem> GetEnumList<TEnum>(TEnum value)
{
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = ((int)v).ToString()
}).ToList();
}
However the above code doesn't compile and gives
Cannot convert type 'TEnum' to 'int'
for the line
Value = ((int)v).ToString()
How do I fix this above code.
Why is it giving a compile error with generic enum and not with a normal enum
Edit: I have tried the suggestions in the thread but I get a further error:
Here is my full code:
public static IHtmlContent EnumDropDownListFor<TModel, TResult,TEnum>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
TEnum enumValue,
string optionLabel)
{
return htmlHelper.DropDownListFor(expression, (IEnumerable<SelectListItem>)GetEnumList(enumValue), optionLabel);
}
public static List<SelectListItem> GetEnumList<TEnum>(TEnum value)
{
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = Convert.ToInt32(v).ToString()
}).ToList();
}
but I get a runtime error
ArgumentException: Type provided must be an Enum.
Parameter name: enumType
on the line
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = Convert.ToInt32(v).ToString()
}).ToList();
What do I need to fix in the code to not get the runtime error.