It's not clear why you've got two Cast<T>
calls anyway, but it's easy enough to do in two steps:
var allValues = (T[]) Enum.GetValues(typeof(T));
var allButDefault = allValues.Except(Enumerable.Repeat(default(T), 1));
Using Except
here avoids boxing, assuming the default comparer does the right thing. Mind you, it will require a set to be built, so you may be better off with my original code:
var allValues = (T[]) Enum.GetValues(typeof(T));
var allButDefault = allValues.Where(t => !t.Equals(default(T)));
Or use the default equality comparer for T
:
var allValues = (T[]) Enum.GetValues(typeof(T));
var comparer = EqualityComparer<T>.Default;
var allButDefault = allValues.Where(t => !comparer.Equals(t, default(T)));
Note that all of these will handle non-int
-based enums too.
You might also want to look at my Unconstrained Melody project which builds on the idea of actually constraining T
to be an enum.
There are various options which you can use for more performance, avoiding creating an array every time etc. We don't know how performance-critical this code is, so I haven't gone into the details here.