Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEnumerable Extension Methods on an Enum

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.

like image 376
ahawker Avatar asked Nov 17 '09 22:11

ahawker


People also ask

Can we extend enum in C#?

Since it's not a class, it cannot be extended and its defined values are limited to a small set of primitive types ( byte , sbyte , short , ushort , int , uint , long , ulong ). For instance, sometimes it is very convenient to get the list of enum values and display it in a combobox.

Can you extend an enum Swift?

We can extend the enum in two orthogonal directions: we can add new methods (or computed properties), or we can add new cases. Adding new methods won't break existing code. Adding a new case, however, will break any switch statement that doesn't have a default case.

How do you declare an extension method?

To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.

What is extension method in Linq?

Extension Methods are a new feature in C# 3.0, and they're simply user-made pre-defined functions. An Extension Method enables us to add methods to existing types without creating a new derived type, recompiling, or modifying the original types.


2 Answers

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>.

like image 52
Andrew Hare Avatar answered Sep 22 '22 00:09

Andrew Hare


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

like image 30
Lee Avatar answered Sep 23 '22 00:09

Lee