Thursday, 28 July 2016

Getting enum values to list of string List<string> C#

So you created an enum and you want to extract all the values to List<string>?

Example enum:


public enum FilterTypeLookup {
Textbox = 1,
Standard_Dropdown = 2,
Extended_Dropdown = 3,
Normal_Dropdown = 4,
Link = 5,
Label = 6,
Checkbox = 7,
Dropdown_with_Textbox_and_Button = 8,
Textbox_with_text_before_and_text_after = 9,
Radio_Button = 10,
Date_Picker = 11,
Month = 12,
Year = 13,
Customer_Dropdown = 14,
AutoComplete = 15
}

Probably the easiest way to do it is to use GetNames method on Enum.

return Enum.GetNames(typeof(FilterTypeLookup )).ToList();


If we want to make it more generic we can write helper method.

 public static List<string> GetNamesForEnums<T>()
        {
            //Type type = t.GetType();
            return Enum.GetNames(typeof(T)).ToList();
        }