'How to get description from Enum and set into dictionary

enter image description here

I was trying to get the enum description in this method.

Is there any way to get the enum description in this method? For example:

Enum.GetValues(typeof(T))
        .Cast<T>()
        .ToDictionary(t => (int)(object)t, t => t.Description.ToString());


Solution 1:[1]

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>());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1