C#
enum
list conversion
programming
beginner tips

How do I convert an enum to a list in C?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Enumerations, or enums, are a special "class" representing a group of constants (unchangeable/read-only variables). Enums are used to create named constants for underlying integral types such as byte, int, etc. Often you might need to convert these enum values into a list for easier processing, iteration, or for use in a UI component. This article provides insights into converting enums to a list in C#.

Understanding Enumerations in C#

Before diving into converting enums to lists, let's brush up on what an enumeration is in C#.

Basic Enum Definition

csharp
1public enum Colors
2{
3    Red,
4    Green,
5    Blue,
6    Yellow
7}

The enum Colors has four named constants (Red, Green, Blue, Yellow). Internally, these are represented as integer values starting at 0 by default, unless explicitly assigned.

Enum to List Conversion

If you want to iterate over the values of an enum or use them as a collection, converting them to a list is a straightforward solution.

Using LINQ to Convert Enums to List

The most common and clean way to convert an enum to a list is by utilizing LINQ (Language Integrated Query):

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public class Program
6{
7    public enum Colors
8    {
9        Red,
10        Green,
11        Blue,
12        Yellow
13    }
14
15    public static void Main()
16    {
17        List<Colors> colorList = Enum.GetValues(typeof(Colors)).Cast<Colors>().ToList();
18
19        foreach (var color in colorList)
20        {
21            Console.WriteLine(color);
22        }
23    }
24}

Explanation

  1. Enum.GetValues: Retrieves an array of the values in the enum.
  2. Cast<T>(): Converts the array to an IEnumerable&lt;T&gt;, specifically to IEnumerable&lt;Colors&gt; in our case.
  3. ToList(): Converts the IEnumerable&lt;Colors&gt; into a List&lt;Colors&gt;.

Alternative Methods

Besides LINQ, there are other methods to perform this conversion:

Using a Loop

Although LINQ simplifies the process significantly, you can manually loop through the enum values:

csharp
1List<Colors> colorList = new List<Colors>();
2foreach (Colors color in Enum.GetValues(typeof(Colors)))
3{
4    colorList.Add(color);
5}

Using Array and ToList

You can first convert the enum to an array and then to a list:

csharp
Colors[] colorArray = (Colors[])Enum.GetValues(typeof(Colors));
List<Colors> colorList = new List<Colors>(colorArray);

Key Considerations

  1. Performance: Using LINQ is generally more concise but might not always be the most performant option for large enums due to additional method calls.
  2. Versioning: Enums in C# are static lists. Once defined and compiled, adding or removing values requires recompilation.
  3. Usages:
    • Converting enums to lists can be particularly useful in user interfaces where you need to display options in combo boxes, drop-down lists, etc.
    • Creating a list allows easier manipulation, such as filtering or sorting.

Summary Table

Here's a concise summary of converting enums to lists:

MethodDescriptionAdvantagesDisadvantages
LINQ CastingUses Enum.GetValues, Cast&lt;T&gt;(), ToList() to convert enum to list.Concise and idiomatic C# codeSlightly increased overhead for large enums
LoopingIterates through Enum.GetValues adding each to a list manually.Straightforward for small enumsVerbose, potentially inefficient for large enums
Array ConversionConverts first to an array and then to a list.Direct and efficientTwo-step conversion, more manual work

Additional Considerations

  • Flags Attribute: Enums can be attributed with [Flags] to be treated as bit fields. Handling these may require additional logic if converting to a list.
  • Serialization: Converting enums into lists could help in scenarios such as serializing to JSON or XML where enums need to be sent over the wire.

By converting enums to lists, you can effectively use them in contexts that require collections, thereby improving the versatility and functionality of your C# applications.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms