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.
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.
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.
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.
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.
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>
.
Array implements IEnumerable so you'll need to use Cast<Suit>
or OfType<Suit>
to get the IEnumerble<T>
extensions like ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With