Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple form of Array class and Enum.GetValues()

Tags:

c#

.net

I am working with the static method

Enum.GetValues(typeof(SomeEnum));

This method works great when all you need to do is enumerate the values, but for some reason it returns a very simple form of the Array class. I am trying to find an easy way to turn it's return value into a more "normal" collection class like a regular array or List<>.

So far if I want to do that I have to enumerate through the output of Enum.GetValues(typeof(SomeEnum)); and add them one by one to a List<>.

Any ideas how to do this more cleanly?

Answer:

The key is to cast the return result --

SomeEnum[] enums = (SomeEnum[]) Enum.GetValues(typeof(SomeEnum));

If you need a List then jus wrap it in parenthesis and ToList it like so:

List<SomeEnum> list = ((SomeEnum[]) Enum.GetValues(typeof(SomeEnum))).ToList();
like image 542
Alex Baranosky Avatar asked Sep 12 '09 04:09

Alex Baranosky


1 Answers

If you're using .NET 3.5, you can also use Cast<T> and ToList extension methods.

IEnumerable<SomeEnum> enums = Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();

You can also get a list if you want to

List<SomeEnum> list =  Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>().ToList();
like image 152
Mehmet Aras Avatar answered Sep 20 '22 08:09

Mehmet Aras