C# Enum to List Conversion

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.

Enum to List in C#

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.

  • Get the type of object we receive, and assign in a type variable.
    Type enumType = typeof(T);
  • Enum object has a built-in method called GetValues, which return values in form of an array.
    Array enumValArray = Enum.GetValues(enumType);
  • Then we create a list object, optionally we can specify the length at the time of creation, though not mandatory.
    List<T> enumValList = new List<T>(enumValArray.Length);
    
  • Finally loop though the array value and add each item to the list.

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

 
C# Convert Enum to List
.Net C# Programming Tutorials
Online Tutorials
C# .net Interview Questions Answers
.Net C# Examples | Join .Net C# Course