Reputation: 167
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
?
Upvotes: 4
Views: 1845
Reputation: 877
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);
Upvotes: 9
Reputation: 101613
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
Upvotes: 4