C# - Convert Enum to List
In C#, you can transform an enumeration into a list by employing the Enum.GetValues
method in conjunction with the LINQ ToList
extension method. The Enum.GetValues
method gets all the enum values in an array, and you can change that array into a list using the ToList
method in the LINQ namespace.
Here's an example:
enum DaysOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
class Program
{
static void Main()
{
List enumList = Enum.GetValues(typeof(DaysOfWeek))
.Cast()
.ToList();
foreach (DaysOfWeek day in enumList)
{
Console.WriteLine(day);
}
}
}
The provided C# program defines an enumeration called DaysOfWeek
, which represents the days of the
week. It then uses the Enum.GetValues
method to obtain an array of all the values defined in the
DaysOfWeek
enumeration, casts each value to the DaysOfWeek
enum type, and finally
converts the resulting array into a List<DaysOfWeek>
using LINQ's Cast
and
ToList
methods. The program then iterates through the enumList
and prints each value to
the console.
Expected Output
Here's the expected output of the program:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Explanation
-
Enum.GetValues(typeof(DaysOfWeek))
: This line retrieves an array of all the values defined in the
DaysOfWeek
enumeration. Since the enum contains the days of the week, it includes Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday, and Sunday.
-
.Cast<DaysOfWeek>()
: The GetValues
method returns an array of type System.Array
,
so we use the Cast
method to convert each element in the array to the DaysOfWeek
enum type.
-
.ToList()
: After casting the values, we convert the resulting sequence into a List<DaysOfWeek>
.
-
The foreach
loop then iterates through each day in the enumList
and prints it to the console
using Console.WriteLine
.
As a result, the program prints the names of the days of the week in the order they are defined in the DaysOfWeek
enumeration, which is the output displayed above.