I\'m having some hard time with trying to be generic with enums. I\'ve read that it\'s not that simple, and I can\'t seem to find a solution.
I\'m trying to create a
Here, try this:
public static KeyValuePair> ConvertEnumWithDescription() where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new Exception("Type given T must be an Enum");
}
var enumType = typeof(T).ToString().Split('.').Last();
var itemsList = Enum.GetValues(typeof(T))
.Cast()
.Select(x => new KeyValueDataItem
{
Key = Convert.ToInt32(x),
Value = GetEnumDescription(x.ToString())
})
.ToList();
var res = new KeyValuePair>(
enumType, itemsList);
return res;
}
public static string GetEnumDescription(string value)
{
Type type = typeof(T);
var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();
if (name == null)
{
return string.Empty;
}
var field = type.GetField(name);
var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
}
Based on: http://www.extensionmethod.net/csharp/enum/getenumdescription