简体   繁体   English

使用LINQ选择枚举中的所有标记值

[英]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. 我想使用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: 通过以下代码可以在普通C#中实现所需的结果:

EnumThing wishedOutcome = ab | ad;

or in SQL by 或者在SQL中

select 3 | 9

But how do I select all selected flags in enumList using Linq into a new EnumThing ? 但是如何使用Linq将enumList所有选定标志选择为新的EnumThing

You can use LINQ Aggregate function: 您可以使用LINQ Aggregate函数:

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. 请注意,如果list为空 - 这将引发异常,因此在执行此操作之前检查list是否为空。

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: 一个简单的linq解决方案是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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