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 ProgramAdditionally you can also add a check to evaluate if arr.GetValue(i) is not null before adding it to the List<>
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
Tweet
3 comments:
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.
If I am not wrong, Enum.GetNames() accepts an enumeration type as a parameter
Exactly. Can't the whole main routine could be reduced to:
var lstDays = Enum.GetNames(typeof(Days));
with the same result?
Post a Comment