The following will provides descriptions for an enum.
public class EnumHelper
{
public static List<KeyValuePair<string, Enum>> GetItemsAsDictionary<T>() =>
Enum.GetValues(typeof(T)).Cast<T>()
.Cast<Enum>()
.Select(value => new KeyValuePair<string, Enum>(
(GetCustomAttribute(value.GetType().GetField(value.ToString())!,
typeof(DescriptionAttribute)) as DescriptionAttribute)!.Description, value))
.ToList();
}
Or with type checking
public static List<KeyValuePair<string, Enum>> GetItemsAsDictionarySafe<T>()
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("Must be an enum");
}
return Enum.GetValues(typeof(T)).Cast<T>()
.Cast<Enum>()
.Select(value => new KeyValuePair<string, Enum>(
(GetCustomAttribute(value.GetType().GetField(value.ToString())!,
typeof(DescriptionAttribute)) as DescriptionAttribute)!.Description, value))
.ToList();
}
Sample Enum
public enum Shapes
{
[Description("A shape with 3 strokes")]
Triangle,
[Description("A rounded shape")]
Circle,
[Description("A shape with 4 corners")]
Square,
[Description("Other option")]
Other
}
Usage
Dictionary<string, Enum> dictionary =
new Dictionary<string, Enum>(EnumHelper.GetItemsAsDictionary<Shapes>());