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.
You've told the compiler nothing about TEnum
. As far as its concerned, it could be a string, a DateTime, a BankAccount, a Bullet or anything.
To get this to work, you can use Enum.Parse
and Convert.ToInt32
UPD: Let me just format the code from comment and fix compilation errors for SO-copy-pasters :D
public static int GetEnumIntValue<T>(T value)
where T : struct
{
Type genericType = typeof(T);
Debug.Assert(genericType.IsEnum);
Enum enumValue = Enum.Parse(genericType, value.ToString()) as Enum;
return Convert.ToInt32(enumValue);
}
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