Enums are a powerful feature of C# that allow you to define a set of named constants. And it can be a challenge to enumerate an Enum in C#. In this article, I will explore the different ways to enumerate an Enum in C#. This can be useful when you need to perform the same operation on all the named constants or when you need to retrieve a list of all the named constants.
How to Enumerate an Enum using GetValues() using Foreach
The GetValues() method returns an array of all the named constants defined in the Enum. There are two variants of how to iterate through the GetValues() result.
enum Colors { Red, Green, Blue } //Variant 1 foreach (Colors color in Enum.GetValues(typeof(Colors))) { Console.WriteLine(color); } Console.WriteLine(Environment.NewLine); //Variant 2 Enum.GetValues(typeof(Colors)) .Cast<Colors>() .ToList() .ForEach(color => Console.WriteLine(color));
How to Enumerate an Enum using GetNames() using Foreach
The GetNames() method is another way to enumerate an Enum in C#. This method returns an array of all the names of the named constants defined in the Enum.
enum Colors { Red, Green, Blue } //Variant 1 foreach (string name in Enum.GetNames(typeof(Colors))) { Console.WriteLine(name); } Console.WriteLine(Environment.NewLine); //Variant 2 Enum.GetNames(typeof(Colors)) .Cast<string>() .ToList() .ForEach(color => Console.WriteLine(color)); //yarkul.com
You can enumerate an Enum using LINQ by using the Where() extension method to filter the named constants and return a collection of the remaining elements.
Enum.GetValues(typeof(Colors)) .Cast<Colors>() .ToList() .Where(color => color == Colors.Red) .ToList() .ForEach(color => Console.WriteLine(color));