将枚举转换为List <string> </string>

时间:2013-02-20 03:09:52

标签: c# .net enums generic-list

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

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

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

2 个答案:

答案 0 :(得分:141)

使用Enum的静态方法GetNames。它会返回string[],如下所示:

Enum.GetNames(typeof(DataSourceTypes))

如果你想创建一个只对一种类型的enum执行此操作的方法,并且还将该数组转换为List,则可以编写如下内容:

public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

答案 1 :(得分:26)

我想添加另一个解决方案: 在我的情况下,我需要在下拉按钮列表项中使用枚举组。所以他们可能有空间,即需要更加用户友好的描述:

  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();
        */

    }