134

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>?

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321

3 Answers3

247

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

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • 11
    @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*. – Jeremy Thompson Sep 23 '14 at 09:16
  • It seems `Enum.GetNames(typeof(DataSourceTypes))` return a generic `System.Array` instead of a string array? – sookie Nov 30 '17 at 17:07
  • @sookie, see the msdn link, this is the signature of the **GetNames()** method: `public static string[] GetNames` – Jeremy Thompson Feb 21 '18 at 07:35
36

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

    }
rkmorgan
  • 487
  • 4
  • 12
  • 1
    Instead of `[Description(` use `[EnumMember(Value =` which *auto deserializes* JSON Enums! Its easy to implement, change: `x => x.GetDescription()` to `x => x.GetAttributeOfType().Value` and the method: `public static T GetAttributeOfType(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 Feb 15 '22 at 03:43
  • The `GetDescription` extension should return `field.Name` if `attr` is null (in case there's no description attribute on a value). – Daz Jun 30 '22 at 11:32
2

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();
        }
    }
}
logeshpalani31
  • 1,416
  • 12
  • 33