我有一个对象集合,每个对象都有一个位字段枚举属性。我想要得到的是整个集合中位字段属性的逻辑或。如何在不循环集合的情况下做到这一点(希望使用 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
因为它简单且不复杂,所以基本就是要走的路线,但这只是我实际使用的简化版本。