Convert an enum to List<string>
Asked Answered
L

3

140

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

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

I couldn't find this exact question, this Enum to List is the closest but I specifically want List<string>?

Lekishalela answered 20/2, 2013 at 3:9 Comment(0)
L
256

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


If you only need a single item in the list:

string enumItemAsString = nameof(DataSourceTypes.Grid)
Lekishalela answered 20/2, 2013 at 3:10 Comment(3)
@DCShannon please do not edit popular questions/answers and shrink explanations. While you and I understand shorthand code, newbie's need all the extra details to associate it with their learnings.Lekishalela
It seems Enum.GetNames(typeof(DataSourceTypes)) return a generic System.Array instead of a string array?Crackleware
@sookie, see the msdn link, this is the signature of the GetNames() method: public static string[] GetNamesLekishalela
E
38

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

    }
Eurythermal answered 9/7, 2014 at 19:0 Comment(2)
Instead of [Description( use [EnumMember(Value = which auto deserializes JSON Enums! Its easy to implement, change: x => x.GetDescription() to x => x.GetAttributeOfType<EnumMemberAttribute>().Value and the method: 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; }Lekishalela
The GetDescription extension should return field.Name if attr is null (in case there's no description attribute on a value).Ferrell
K
3

In my case, I need to convert it as SelectItem for Checkbox and Radio Button

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();
        }
    }
}
Kyle answered 6/7, 2022 at 7:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.