开发者

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

开发者 https://www.devze.com 2023-03-04 07:25 出处:网络
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. How can I do thi

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. How can I do this with out looping over the collection (hopefully using LINQ and a lambda instead)?

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:

return MyFoos.Aggregate<Foo>((runningAttributes, nextAttributes) => 
    runningAttributes | nextAttribute);
开发者_JAVA技巧

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?

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.


Your query doesn't work, because you're trying to apply | on Foos, not on Attributes. What you need to do is to get MyAttributes for each Foo in the collection, which is exaclty what Select() does:

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.

Then, I think the code you’re looking for is:

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

精彩评论

暂无评论...
验证码 换一张
取 消