将枚举转换为List<string>

138

如何将以下枚举类型转换为字符串列表?

[Flags]
public enum DataSourceTypes
{
    None = 0,
    Grid = 1,
    ExcelFile = 2,
    ODBC = 4
};

我找不到这个确切的问题,这个Enum to List最接近,但我特别想要List<string>

3个回答

254
使用Enum的静态方法GetNames。它返回一个string[],如下所示:
Enum.GetNames(typeof(DataSourceTypes))

如果你想创建一个仅针对一种类型的enum执行此操作,并将该数组转换为List的方法,你可以编写类似以下的代码:
public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

你需要在你的类顶部使用Using System.Linq;来使用.ToList()。
如果你只需要列表中的一个项目:
string enumItemAsString = nameof(DataSourceTypes.Grid)

11
@DCShannon,请不要编辑热门问题/答案并缩小解释。虽然您和我都了解速记代码,但新手需要所有额外的细节来将其与他们的学习联系起来。请确保翻译内容通俗易懂,但不要改变原意。 - Jeremy Thompson
似乎 Enum.GetNames(typeof(DataSourceTypes)) 返回的是一个通用的 System.Array,而不是一个字符串数组? - sookie
@sookie,请查看 MSDN 链接,这是 GetNames() 方法的签名:public static string[] GetNames - Jeremy Thompson

37
我想再提供一个解决方案: 在我的情况下,我需要在下拉按钮列表项中使用枚举组。因此,它们可能包含空格,即需要更加用户友好的描述:
  public enum CancelReasonsEnum
{
    [Description("In rush")]
    InRush,
    [Description("Need more coffee")]
    NeedMoreCoffee,
    [Description("Call me back in 5 minutes!")]
    In5Minutes
}

在一个帮助类(HelperMethods)中,我创建了以下方法:
 public static List<string> GetListOfDescription<T>() where T : struct
    {
        Type t = typeof(T);
        return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
    }

当您调用此助手时,您将获得项目描述列表。
 List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();

补充: 无论如何,如果您想实现此方法,您需要枚举的:GetDescription扩展。这就是我使用的。

 public static string GetDescription(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            FieldInfo field = type.GetField(name);
            if (field != null)
            {
                DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return null;
        /* how to use
            MyEnum x = MyEnum.NeedMoreCoffee;
            string description = x.GetDescription();
        */

    }

1
不要使用[Description()],而是使用[EnumMember(Value =)],它可以自动反序列化JSON枚举! 它很容易实现,将x => x.GetDescription()更改为x => x.GetAttributeOfType <EnumMemberAttribute>()。 Value并更改方法:public static T GetAttributeOfType <T>(this Enum enumVal)where T:System.Attribute {var type = enumVal.GetType(); var memInfo = type.GetMember(enumVal.ToString()); var attributes = memInfo [0] .GetCustomAttributes(typeof(T),false); return(attributes.Length> 0)?(T)attributes [0]:null; } - Jeremy Thompson
如果attr为空(即值上没有描述属性),则GetDescription扩展应返回field.Name - Daz

3
在我的情况下,我需要将它转换为复选框和单选按钮的SelectItem
public class Enum<T> where T : struct, IConvertible
{
    public static List<SelectItem> ToSelectItems
    {
        get
        {
            if (!typeof(T).IsEnum)
                throw new ArgumentException("T must be an enumerated type");
            
            var values = Enum.GetNames(typeof(T));
            return values.Select((t, i) => new SelectItem() {Id = i, Name = t}).ToList();
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接