Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Flag Enum get Attributes from values

Greetings StackOverflow,

If I've got an enum type with the Flag attribute as well as the values in this enum type with their own attributes, how can I retrieve all of the appropriate attributes?

For example:

[Flags()]
enum MyEnum
{
    [EnumDisplayName("Enum Value 1")]
    EnumValue1 = 1,
    [EnumDisplayName("Enum Value 2")]
    EnumValue2 = 2,
    [EnumDisplayName("Enum Value 3")]
    EnumValue3 = 4,
}

void Foo()
{
    var enumVar = MyEnum.EnumValue2 | MyEnum.EnumValue3;

    // get a collection of EnumDisplayName attribute objects from enumVar
    ...
}
like image 694
LamdaComplex Avatar asked Jul 10 '26 08:07

LamdaComplex


1 Answers

A quick and dirty way using Linq:

IEnumerable<EnumDisplayNameAttribute> attributes = 
    Enum.GetValues(typeof(MyEnum))
        .Cast<MyEnum>()
        .Where(v => enumVar.HasFlag(v))
        .Select(v => typeof(MyEnum).GetField(v.ToString()))
        .Select(f => f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), false)[0])
        .Cast<EnumDisplayNameAttribute>();

Or in query syntax:

IEnumerable<EnumDisplayNameAttribute> attributes = 
    from MyEnum v in Enum.GetValues(typeof(MyEnum))
    where enumVar.HasFlag(v)
    let f = typeof(MyEnum).GetField(v.ToString())
    let a = f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), false)[0]
    select ((EnumDisplayNameAttribute)a);

Alternatively, if there could possibly be multiple attributes on each field, you'll probably want to do this:

IEnumerable<EnumDisplayNameAttribute> attributes = 
    Enum.GetValues(typeof(MyEnum))
        .Cast<MyEnum>()
        .Where(v => enumVar.HasFlag(v))
        .Select(v => typeof(MyEnum).GetField(v.ToString()))
        .SelectMany(f => f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), false))
        .Cast<EnumDisplayNameAttribute>();

Or in query syntax:

IEnumerable<EnumDisplayNameAttribute> attributes = 
    from MyEnum v in Enum.GetValues(typeof(MyEnum))
    where enumVar.HasFlag(v))
    let f = typeof(MyEnum).GetField(v.ToString())
    from EnumDisplayNameAttribute a in f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), false)
    select a;
like image 121
p.s.w.g Avatar answered Jul 11 '26 21:07

p.s.w.g