Enum to list as an extension?

后端 未结 6 1308
花落未央
花落未央 2021-02-19 19:00

I have various enums that I use as sources for dropdown lists, In order to provide for a user-friendly description, I added a Description attribute to each enum, an

6条回答
  •  臣服心动
    2021-02-19 19:44

    I have this extension method in my stack and use it for the same thing all the time.

    public static string Description(this Enum @enum)
    {
        try
        {
            var @string = @enum.ToString();
    
            var attribute =
                @enum.GetType()
                     .GetField(@string)
                     .GetCustomAttribute(false);
    
            return attribute != null ? attribute.Description : @string;
        }
        catch // Log nothing, just return an empty string
        {
            return string.Empty;
        }
    }
    

    Example usage:

    MyEnum.Value.Description(); // The value from within the description attr.
    

    Additionally, you can use this one to get a IDictionary for binding purposes.

    public static IDictionary ToDictionary(this Type type)
    {
        if (!type.IsEnum)
        {
            throw new InvalidCastException("'enumValue' is not an Enumeration!");
        }
    
        var names = Enum.GetNames(type);
        var values = Enum.GetValues(type);
    
        return Enumerable.Range(0, names.Length)
                         .Select(index => new
                         {
                             Key = names[index],
                             Value = ((Enum)values.GetValue(index)).Description()
                         })
                         .ToDictionary(k => k.Key, k => k.Value);
    }
    

    Use it like so:

    var dictionary = typeof(MyEnum).ToDictionary();
    

    Update

    Here is a working .NET Fiddle.

    public static Dictionary ToDictionary(this Type type)
        where TEnum : struct, IComparable, IFormattable, IConvertible
    {
        return Enum.GetValues(type)
                   .OfType()
                   .ToDictionary(value => value, value => value.Description());
    }
    

    Then use it like this:

    public enum Test
    {
        [Description("A test enum value for 'Foo'")]
        Foo,
        [Description("A test enum value for 'Bar'")]
        Bar
    }
    
    typeof(Test).ToDictionary()
    

提交回复
热议问题