简体   繁体   中英

Get description attribute of an enum *subset*

I know how to get the description of every enum. I am trying to figure out how to get it of a subset .

Here's what I have, which I trust shows the intent of what I'm aiming for:

public enum ModelType : int
{
    /// <summary>
    /// No model type. For internal use only.
    /// </summary>
    [Description("NA")]
    _NA = 0,  

    [Description("Literal Model")]
    Literal = 1,

    [Description("Linear Model")]
    Linear = 2,

    [Description("Curve Model")]
    Curve = 3
}


var values = Enum.GetValues(typeof(ModelType))
    .Cast<ModelType>()
    .Where(x => x > ModelType._NA)  // filter
    .ToArray();

var attributes = values.GetMembers() // this is wrong
    .SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>())
    .ToList();

return attributes.Select(x => x.Description);

This should work:

var type = typeof(ModelType);

var propNames = Enum.GetValues(type)
    .Cast<ModelType>()
    .Where(x => x > ModelType._NA)  // filter
    .Select(x => x.ToString())
    .ToArray();

var attributes = propNames
    .Select(n => type.GetMember(n).First())
    .SelectMany(member => member.GetCustomAttributes(typeof(DescriptionAttribute), true).Cast<DescriptionAttribute>())
    .ToList();

return attributes.Select(x => x.Description);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM