Search code examples
c#linqenumsenum-flags

Select all flagged values in enum using LINQ


I have a collection of flagged enums, like this:

[Flags]
enum EnumThing
{
    A = 1,
    B = 2,
    C = 4,
    D = 8
}

I'd like to select all flags in the collection using LINQ. Let's say that the collection is this:

EnumThing ab = EnumThing.A | EnumThing.B;
EnumThing ad = EnumTHing.A | EnumThing.D;    
var enumList = new List<EnumThing> { ab, ad };

In bits it will look like this:

0011
1001

And the desired outcome like this:

1011

The desired outcome could be achieved in plain C# by this code:

EnumThing wishedOutcome = ab | ad;

or in SQL by

select 3 | 9

But how do I select all selected flags in enumList using Linq into a new EnumThing?


Solution

  • A simple linq solution would be this:

    EnumThing ab = EnumThing.A | EnumThing.B;
    EnumThing ad = EnumThing.A | EnumThing.D;
    var enumList = new List<EnumThing> { ab, ad };
    
    var combined = enumList.Aggregate((result, flag) => result | flag);