Friday, February 27, 2009

Getting all entries in an Enum as a list

I needed some code to get each field in an enum as its enum type and not just its string name or value. Most example on the web seem to use reflection, or getting the name and converting that to an enum, I wanted a simpler way:

User[] allValues = (User[])Enum.GetValues(typeof (User));
List<User> allUserFields = new List<User>(allValues);

That was the easiest way I could find, and is good enough for now, but maybe someone else has a nicer way...?

Alternatively you can get the List directly using:

((User[])Enum.GetValues(typeof (User))).ToList()

However if you need todo any processing on the list I find the first way more readable.

No comments:

Post a Comment