Get values ​​from enum to general list

I do not 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 does not 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 is not perceived as follows: what cast (or else) am I missing?

For clarification: it is wrapped in the following general method

 public static void BindToEnum<T>() { List<T> values = new List<T>(System.Enum.GetValues(typeof(T))); //... } 
+4
source share
3 answers

Using LINQ:

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

Just add .Cast<T>() :

 List<T> values = new List<T>(System.Enum.GetValues(typeof(T)).Cast<T>()); 
+3
source

Based on this post, I created a function for myself to do this for me; This is great in Unit Tests, when you want to iterate over all Enum values ​​to verify that something works only with certain values.

 public static IEnumerable<T> GetEnumValues<T>() { return Enum.GetValues(typeof(T)).Cast<T>(); } 

Then I can use it like this:

 var values = GetEnumValues<SomeTypeCode>(); var typesToAlwaysShow = values.Where(ScreenAdapter.AlwaysShowThisType).Select(q => (int)q).ToList(); Assert.Equal("101,102,105,205", string.Join(",", typesToAlwaysShow)); 
0
source

Source: https://habr.com/ru/post/1382291/


All Articles