Convert Enum to List<> using C# or VB.NET

A user recently asked me how to convert an Enum to a List<>. Here’s the code to do so:

C#

class Program
{
enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };

static void Main(string[] args)
{
Array arr = Enum.GetValues(typeof(Days));
List<string> lstDays = new List<string>(arr.Length);
for (int i = 0; i < arr.Length; i++)
{
lstDays.Add(arr.GetValue(i).ToString());
}
}
}

VB.NET

Friend Class Program
Private Enum Days
Sat
Sun
Mon
Tue
Wed
Thu
Fri
End Enum

Shared Sub
Main(ByVal args() As String)
Dim arr As Array = System.Enum.GetValues(GetType(Days))
Dim lstDays As New List(Of String)(arr.Length)
For i As Integer = 0 To arr.Length - 1
lstDays.Add(arr.GetValue(i).ToString())
Next i
End Sub
End Class
Additionally you can also add a check to evaluate if arr.GetValue(i) is not null before adding it to the List<>




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

3 comments:

Harley Pebley said...

Just curious: any reason not to use Enum.GetNames?

(It returns a string array. I suppose if you need a list, you can use Linq's ToList() method.)

Cheers.

Suprotim Agarwal said...

If I am not wrong, Enum.GetNames() accepts an enumeration type as a parameter

Harley Pebley said...

Exactly. Can't the whole main routine could be reduced to:

var lstDays = Enum.GetNames(typeof(Days));

with the same result?