Get a list of available listings.

I have an enumeration structure as follows:

public enum MyEnum
{
   One=1,
   Two=2,
   Three=3
}

Now I want to get a list MyEnum, i.e. List<MyEnum>Which contains all One, Two Three. Again , I am looking for one liner that does this. I came out with a LINQ query, but that was unsatisfactory because it was too long, I think:

Enum.GetNames(typeof(MyEnum))
                            .Select(exEnum =>
                                (MyEnum)Enum.Parse(typeof(MyEnum), exEnum))
                            .ToList();

Best deal?

+5
source share
3 answers
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();
+14
source

I agree with the @mquander code.

However, I would advise you to cache the list as well, as it is unlikely to change during the execution of your program. Put it in readonly static variable at some global location:

public static class MyGlobals
{
   public static readonly List<MyEnum> EnumList = 
       Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().ToList();
}
+3
source

( , : P), , , - this tools/utility, :

public static List<T> EnumToList<T>()

{

 Type enumType = typeof(T);

 // Can't use type constraints on value types, so have to do check like this

 if (enumType.BaseType != typeof(Enum))

  throw new ArgumentException("T must be of type System.Enum");

 return new List<T>(Enum.GetValues(enumType) as IEnumerable<T>);

}
+2

All Articles