Get values from an enum into a generic List

11,535

Solution 1

Using LINQ:

List<T> list = System.Enum.GetValues(typeof(T))
                          .Cast<T>()
                          .ToList<T>();

Solution 2

Just add a .Cast<T>():

List<T> values = new List<T>(System.Enum.GetValues(typeof(T)).Cast<T>());
Share:
11,535
sl3dg3
Author by

sl3dg3

Updated on September 14, 2022

Comments

  • sl3dg3
    sl3dg3 over 1 year

    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)));
        //...
    }
    
  • Remco te Wierik
    Remco te Wierik over 3 years
    Can be improved by adding where T : Enum