Enum Description to String

c#, enums

Solution

You can use this:

var values = x.ToString()
             .Split(new[] { ", " }, StringSplitOptions.None)
             .Select(v => (DataFiat)Enum.Parse(typeof(DataFiat), v));

To get the individual values. Then get the attribute values of them.

Something like this:

var y2 = values.GetAttributes<DescriptionAttribute, DataFiat>();

public static T[] GetAttributes<T, T2>(this IEnumerable<T2> values) where T : Attribute
{
    List<T> ts =new List<T>();

    foreach (T2 value in values)
    {
        T attribute;
        MemberInfo info = value.GetType().GetMember(value.ToString()).FirstOrDefault();
        if (info != null)
        {
            attribute = (T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault();
            ts.Add(attribute);
        }
    }

    return ts.ToArray();
}

Problem

I have the following ENUM: ``` [Flags] public enum DataFiat { [Description("Público")] Public = 1, [Description("Filiado")] Listed = 2, [Description("Cliente")] Client = 4 } // DataFiat ``` And I created an extension to get an Enum attribute: ``` public static T GetAttribute<T>(this Enum value) where T : Attribute { T attribute; MemberInfo info = value.GetType().GetMember(value.ToString()).FirstOrDefault(); if (info != null) { attribute = (T)info.GetCustomAttributes(typeof(T), false).FirstOrDefault(); return attribute; } return null; } ``` This works for non Flags Enums ... But when I have: ``` var x = DataFiat.Public | DataFiat.Listed; var y = x.GetAttribute<Description>(); ``` The value of y is null ... I would like to get "Público, Filiado, Cliente" ... Just as ToString() works. How can I change my extension to make this work? Thank You

Original source

Related problems