Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get values from an enum into a generic List

I don't know how to convert the following line from VB to C#:

Dim values As New List(Of T)(System.Enum.GetValues(GetType(T)))

My version doesn't work:

List<T> values = new List<T>(System.Enum.GetValues(typeof(T)));

The best overloaded method match for 'System.Collections.Generic.List.List(System.Collections.Generic.IEnumerable)' has some invalid arguments

The constructor-parameter doesn't take it that way - what cast (or else) am I missing?

For clarification: It is wrapped up within the following generic method

public static void BindToEnum<T>()
{
    List<T> values = new List<T>(System.Enum.GetValues(typeof(T)));
    //...
}
like image 631
sl3dg3 Avatar asked Nov 21 '11 14:11

sl3dg3


1 Answers

Using LINQ:

List<T> list = System.Enum.GetValues(typeof(T))
                          .Cast<T>()
                          .ToList<T>();
like image 182
sll Avatar answered Oct 05 '22 17:10

sll