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



我有一个对象的集合,每个对象都有一个位字段枚举属性。我试图得到的是整个集合中位字段属性的逻辑 OR。如何在不循环访问集合的情况下执行此操作(希望使用 LINQ 和 lambda 代替)?

下面是我的意思的一个例子:

[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? 
    }
}

我尝试使用这样的.Aggregate

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

但这不起作用,我不知道如何使用它来获得我想要的东西。有没有办法使用 LINQ 和一个简单的 lambda 表达式来计算这个问题,还是我只在集合上使用循环?

注意:是的,这个示例案例非常简单,基本的foreach将是要走的路线,因为它简单且不复杂,但这只是我实际使用的精简版本。

您的查询不起作用,因为您尝试在 Foo s 上应用|,而不是在Attributes上应用。您需要做的是为集合中的每个Foo获取MyAttributes,这是Select()所独有的:

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

首先,您需要公开MyAttributes,否则无法从Baz访问它。

然后,我认为您正在寻找的代码是:

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

最新更新