jQuery and ASP.NET

December 7, 2009

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<>

'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

3 Responses to "Convert Enum to List<> using C# or VB.NET"
  1. Harley Pebley said...
    December 7, 2009 11:56 AM

    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.

  2. Suprotim Agarwal said...
    December 7, 2009 7:30 PM

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

  3. Harley Pebley said...
    December 19, 2009 9:51 AM

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

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

    with the same result?

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions