Sometimes we need to display all the enum options on user interface, so that end user can select some item from options, to do that, we need to convert the enum to a list object.
Think of business requirement like where we have to display order status on a webpage, so user can change the status like example below.
enum OrderSatus { Delivered = 1, Received = 2, Cancelled = 3, Returned = 4 }
In dropdown list the status may look like
In this context we learn, how to convert Enum to List in C# .Net programming.
Here is my enum EventState, now i want to display in UI as a list object in dropdown control, So i need to convert the enum to a list object
enum EventState { Initiated = 1, Started = 2, Closed = 3, Canceled = 4 }
This is a static method that converts enum to a generic List type, the below function can be split into four steps.
Type enumType = typeof(T);
Array enumValArray = Enum.GetValues(enumType);
List<T> enumValList = new List<T>(enumValArray.Length);
public static List<T> EnumToList<T>() { Type enumType = typeof(T); // You can't use type constraints on value types, so have to check & throw error. if (enumType.BaseType != typeof(Enum)) throw new ArgumentException("T must be of type System.Enum type"); Array enumValArray = Enum.GetValues(enumType); List<T> enumValList = new List<T>(enumValArray.Length); foreach (int val in enumValArray) { enumValList.Add((T)Enum.Parse(enumType, val.ToString())); } return enumValList; }
Above EnumToList method return a list object and accept a generic type, where we pass the enum object. so finally, call the above method, pass enum as parameter to get the List.
public static List<EventState> GetEventStates() { List<EventState> eventStates = EnumToList<EventState>(); return eventStates; }
Above method you can write as extension method in your project, so using with different enum to list would be easier.
Learn more about C# Enums in .Net