4

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?

Br2
  • 167
  • 1
  • 10
  • Possible duplicate of [Most efficient way to parse a flagged enum to a list](https://stackoverflow.com/questions/3668496/most-efficient-way-to-parse-a-flagged-enum-to-a-list) – Mikolaytis Dec 15 '17 at 11:05
  • 2
    I suppose you meant `EnumThing ab = EnumThing.A *|* EnumThing.B;`? – Evk Dec 15 '17 at 11:14

2 Answers2

8

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);
Jakub Rusilko
  • 859
  • 12
  • 17
4

You can use LINQ Aggregate function:

var desiredOutcome = enumList.Aggregate((x, y) => x | y);

Note that if list is empty - that will throw an exception, so check if list is empty before doing that.

var desiredOutcome = enumList.Count > 0 ? 
    enumList.Aggregate((x, y) => x | y) : 
    EnumThing.Default; // some default value, if possible
Evk
  • 98,527
  • 8
  • 141
  • 191