5

I have the enum structure as follows:

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

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

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

A better suggestion?

Community
  • 1
  • 1
Graviton
  • 81,782
  • 146
  • 424
  • 602

3 Answers3

14
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();
mqp
  • 70,359
  • 14
  • 95
  • 123
3

I agree with @mquander's code.

However, I would suggest you also cache the list, since it's extremely unlikely to change over the course of the execution of your program. Put it in a static readonly variable in some global location:

public static class MyGlobals
{
   public static readonly List<MyEnum> EnumList = 
       Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().ToList();
}
Randolpho
  • 55,384
  • 17
  • 145
  • 179
2

Not a one liner (well the implementation isn't, but the method is :P), but perhaps add something like this to a tools/ utility class which will return a generic list:

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>);

}
Bayard Randel
  • 9,930
  • 3
  • 42
  • 46