.NET Flag Enum get Attributes from values

心不动则不痛 提交于 2019-12-01 20:15:56

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!