Konrad Viltersten
Konrad Viltersten

Reputation: 39068

How to list all the elements from enum into IEnumerable array of the same type?

I'm doing something like this.

IEnumerable<Poof> poofs = new[]{ Poof.One, Poof.Two };

I though it'd be cooler to just fetch all the elements of the enum, so I went like this.

foreach(Poof poof in Enum.GetValues(typeof (Poof)))
  Console.WriteLine(poof);

The above works, as far as I can see the values printed to the screen. However, when I try to store the result I get problems. Why is it so and how can I counter this?

IEnumerable<Poof> poofs = Enum.GetValues(typeof (Poof));

Upvotes: 2

Views: 343

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

IEnumerable<Poof> poofs = Enum.GetValues(typeof(Poof)).OfType<Poof>()

Since you know all the elements are Poof, you can use Cast, but when you don't know what types do you have in the collection you can use OfType.The only difference between them is that Cast, casts the items to specified type without a check but OfType checks each type and if it is convertible to specified type then casts it and returns.It is implemented like this:

static IEnumerable<TResult> OfTypeIterator<TResult>(IEnumerable source) 
{
    foreach (object obj in source) {
         if (obj is TResult) yield return (TResult)obj;
}

Upvotes: 2

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

Enum.GetValues returns an Array which implements IEnumerable and not IEnumerable<Poof>. So you need a cast.

IEnumerable<Poof> poofs = Enum.GetValues(typeof(Poof))
                              .Cast<Poof>();

or

IEnumerable<Poof> poofs = (IEnumerable<Poof>)Enum.GetValues(typeof(Poof));

Upvotes: 2

Related Questions