var query = Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.Except(new MyEnum[] { MyEnum.A, MyEnum.E });
foreach (MyEnum item in query) {
...
}
You need to cast in order to get the magic of LINQ. Except
alone will not do it.
UPDATE:
I got another idea. You can define the enum with the FlagsAttribute
and define the regular values as powers of 2, what is most easily achieved with the bitwise shift left operator <<
. Starting with C# 7.0, you can also use binary literals like 0b_0000_0000_0010_0000
. Then it is possible to combine existing values to form new values.
[Flags]
enum MyEnum
{
None = 0,
A = 1 << 0,
B = 1 << 1,
C = 1 << 2,
D = 1 << 3,
E = 1 << 4,
...
X = 1 << 23,
Y = 1 << 24,
Z = 1 << 25,
Vowels = A | E | I | O | U
}
Now, you can formulate the query like this
IEnumerable<MyEnum> query = Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.Where(x => (x & MyEnum.Vowels) == MyEnum.None);
foreach (MyEnum item in query) {
...
}
The advantage over the first solution is, that you can perform the test with a single bitwise AND-operation.
You can define up to 32 powers of two. If you need more, you can define the base type of the enum as long
and use up to 64 flag values (plus combinations of existing flag values).
[Flags]
enum MyEnum : long
{
...
}