Flagged Enum Consolidation (Inverse of Combination) Using LINQ

302 Views Asked by At

I am trying to generate an inverse of a flagged enumeration. Below is the enum:

[Flags]
public enum MyType
{
  Unknown = 0,
  A = 1 << 0,
  B = 1 << 2,
  C = 1 << 3,
  D = 1 << 4,
  E = 1 << 5,
  F = 1 << 6
}

I have defined a static MyType mtGroup1 with a value of (A | B). I would like to generate the inverse of this, excluding Unknown.

My solution:

MyType t = MyType.Unknown;
foreach (var vType in Enum.GetValues(typeof(MyType)).OfType<MyType>())
{
    if ((mtGroup1 & vType) != vType)
         t = t | vType;   //Consolidates into a single enum, excluding unknown
}

The resulting value of t is C | D | E | F, which is the desired outcome. This method works, but I was hoping there was a more simple way to consolidate as shown above using LINQ (other, non-LINQ ways are also acceptable if simpler).

Thanks!

1

There are 1 best solutions below

2
On BEST ANSWER

My Unconstrained Melody project makes this really simple:

MyType inverse = mtGroup1.UsedBitsInverse();

The project contains a number of useful methods (many written as extension methods) which use "unspeakable" generic constraints (ones which are understood by the C# compiler but can't be expressed in C#) to constrain generic type parameters to be enum types or delegates. In this way, the above code manages to work without any boxing - and it actually works out all the "interesting" bits of an enum type once, the first time that type is used in conjunction with Unconstrained Melody, so this operation is blindingly efficient.

If you don't want to use Unconstrained Melody, you could write your own method to find the "used bits" of an enum once, then just use:

MyType t = UsedBitsOfMyType & ~mtGroup1;