Convert enum to list <string>

How to convert the next enum to a list of strings?

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

I could not find this exact question, this Enum to List is the closest, but I specifically want a List<string>

+61
enums c # generic-list
Feb 20 '13 at 3:09
source share
2 answers

Use the static method Enum , GetNames . It returns a string[] , for example:

 Enum.GetNames(typeof(DataSourceTypes)) 

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

 public List<string> GetDataSourceTypes() { return Enum.GetNames(typeof(DataSourceTypes)).ToList(); } 
+107
Feb 20 '13 at 3:10
source share

I want to add another solution: In my case, I need to use the Enum group in the button list items down. Thus, they may have a place, that is, a more convenient description is required:

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

In the 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 a 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 listing. 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(); */ } 
+16
Jul 09 '14 at 19:00
source share



All Articles