I have a simple class SelectItemOption
that is used generically in dropdowns, lists, etc.
public class SelectItemOption
{
public string Title { get; set; }
public string ID { get; set; }
public string Description { get; set; }
}
I want to create a method that populates a List<SelectItemOption>
with values from an Enum. GetDisplayName()
and GetDisplayDescription()
get this info from the attributes.
I robbed some code from another SO answer to get the enum values into an enumerable.
public static IEnumerable<T> EnumToList<T>()
where T : struct
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
I am attempting to put it all together like this:
public static List<SelectItemOption> EnumAsSelectItemOptions<T>()
where T : struct
{
var optionsList = new List<SelectItemOption>();
foreach (var option in EnumToList<T>()) //** headache here **
{
optionsList.Add(new SelectItemOption()
{
Title = option.GetDisplayName(),
ID = option.ToString(),
Description = option.GetDisplayDescription()
});
}
return optionsList;
}
The problem occurs when I try to iterate EnumToList.
No matter what I try, I can't seem to get the option
variable to act like an Enum.
I've Tried...
If I use foreach (Enum option in EnumToList<T>())
I get "cannot convert type T to system.enum".
But if I use foreach (var option in EnumToList<T>())
my extension methods aren't recognised.
If I try to cast option
as an Enum after the foreach statement I get "cannot implicitly convert type T to system.enum".
Aaaaggggghhhhh!