views:

533

answers:

2

I have an enum(below) that I want to be able to use a LINQ extension method on.

enum Suit{
    Hearts = 0,
    Diamonds = 1,
    Clubs = 2,
    Spades = 3
}

Enum.GetValues(...) is of return type System.Array, but I can't seem to get access to a ToList() extension or anything else of that sort.

I'm just looking to write something like...

foreach(Suit s in Enum.GetValues(typeof(Suit)).Select(x=>x).Where(x=> x != param)){}

Is there something I'm missing, or can someone explain to me why this isn't possible?

Thanks.

+7  A: 

Enum.GetValues returns a System.Array and System.Array only implements IEnumerable rather than IEnumerable<T> so you will need to use the Enumerable.OfType extension method to convert the IEnumerable to IEnumerable<Suit> like this:

Enum.GetValues(typeof(Suit))
      .OfType<Suit>()
      .Where(x => x != param);

Edit: I removed the call to IEnumerable.Select as it was a superfluous projection without any meaningful translation. You can freely filter the IEnumerable<Suit> that is returned from OfType<T>.

Andrew Hare
I tend to see `OfType` more appropriate for when you're looking to filter a list, and `Cast` for casting. Is there a reason to use `Int32` rather than `Suit`?
Nader Shirazie
For any `IEnumerable` that contains homogeneous types, `OfType<T>` and `Cast<T>` will perform and behave virtually identically. As for using `Int32` rather than `Suit` I am not really sure why I did that - my answer has been corrected.
Andrew Hare
Works just like I was looking for. Thanks!
Hawker
+3  A: 

Array implements IEnumerable so you'll need to use Cast<Suit> or OfType<Suit> to get the IEnumerble<T> extensions like ToList();

Lee