Convert an enum to List

后端 未结 2 1322
自闭症患者
自闭症患者 2020-12-04 20:41

How do I convert the following Enum to a List of strings?

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


        
相关标签:
2条回答
  • 2020-12-04 20:59

    Use Enum's static method, GetNames. It returns a string[], like so:

    Enum.GetNames(typeof(DataSourceTypes))
    

    If you want to create a method that does only this for only one type of enum, and also converts that array to a List, you can write something like this:

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

    You will need Using System.Linq; at the top of your class to use .ToList()

    0 讨论(0)
  • 2020-12-04 21:16

    I want to add another solution: In my case, I need to use a Enum group in a drop down button list items. So they might have space, i.e. more user friendly descriptions needed:

      public enum CancelReasonsEnum
    {
        [Description("In rush")]
        InRush,
        [Description("Need more coffee")]
        NeedMoreCoffee,
        [Description("Call me back in 5 minutes!")]
        In5Minutes
    }
    

    In a helper class (HelperMethods) I created the following method:

     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();
        }
    

    When you call this helper you will get the list of item descriptions.

     List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();
    

    ADDITION: In any case, if you want to implement this method you need :GetDescription extension for enum. This is what I use.

     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();
            */
    
        }
    
    0 讨论(0)
提交回复
热议问题