简体   繁体   English

如何使用LINQ和lambdas对列表中对象的位标志枚举属性执行按位OR?

[英]How can I use LINQ and lambdas to perform a bitwise OR on a bit flag enumeration property of objects in a list?

I have a collection of objects, and each object has a bit field enumeration property. 我有一个对象集合,每个对象都有一个位字段枚举属性。 What I am trying to get is the logical OR of the bit field property across the entire collection. 我想要得到的是整个集合中位字段属性的逻辑OR。 How can I do this with out looping over the collection (hopefully using LINQ and a lambda instead)? 如何通过循环遍历集合(希望使用LINQ和lambda)来完成此操作?

Here's an example of what I mean: 这是我的意思的一个例子:

[Flags]
enum Attributes{ empty = 0, attrA = 1, attrB = 2, attrC = 4, attrD = 8}

class Foo {
    Attributes MyAttributes { get; set; }
}

class Baz {
    List<Foo> MyFoos { get; set; }

    Attributes getAttributesOfMyFoos() {
        return // What goes here? 
    }
}

I've tried to use .Aggregate like this: 我试过像这样使用.Aggregate

return MyFoos.Aggregate<Foo>((runningAttributes, nextAttributes) => 
    runningAttributes | nextAttribute);

but this doesn't work and I can't figure out how to use it to get what I want. 但这不起作用,我无法弄清楚如何使用它来得到我想要的东西。 Is there a way to use LINQ and a simple lambda expression to calculate this, or am I stuck with just using a loop over the collection? 有没有办法使用LINQ和一个简单的lambda表达式来计算这个,或者我只是在集合上使用循环?

Note: Yes, this example case is simple enough that a basic foreach would be the route to go since it's simple and uncomplicated, but this is only a boiled down version of what I am actually working with. 注意:是的,这个示例案例很简单,基本的foreach将成为foreach的路线,因为它简单而且不复杂,但这只是我实际使用的简化版本。

Your query doesn't work, because you're trying to apply | 您的查询不起作用,因为您正在尝试应用| on Foo s, not on Attributes . Foo ,而不是在Attributes What you need to do is to get MyAttributes for each Foo in the collection, which is exaclty what Select() does: 你需要做的是为集合中的每个Foo获取MyAttributes ,这与Select()作用相同:

MyFoos.Select(f => f.MyAttributes).Aggregate((x, y) => x | y)

First, you'll need to make MyAttributes public, otherwise you can't access it from Baz . 首先,您需要公开MyAttributes ,否则您无法从Baz访问它。

Then, I think the code you're looking for is: 然后,我认为您正在寻找的代码是:

return MyFoos.Aggregate((Attributes)0, (runningAttributes, nextFoo) => 
    runningAttributes | nextFoo.MyAttributes);

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

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