简体   繁体   中英

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 ?

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM