Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a List of available Enums

Tags:

c#

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?

like image 673
Graviton Avatar asked Apr 24 '09 01:04

Graviton


2 Answers

Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();
like image 51
mqp Avatar answered Sep 27 '22 20:09

mqp


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();
}
like image 29
Randolpho Avatar answered Sep 27 '22 21:09

Randolpho