10

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

4

2 回答 2

24

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

MyFoos.Select(f => f.MyAttributes).Aggregate((x, y) => x | y)
于 2011-05-10T00:03:51.970 回答
2

首先,您需要MyAttributes公开,否则您无法从Baz.

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

return MyFoos.Aggregate((Attributes)0, (runningAttributes, nextFoo) => 
    runningAttributes | nextFoo.MyAttributes);
于 2011-05-10T00:04:23.370 回答