Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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);

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.

like image 257
cdeszaq Avatar asked May 09 '11 23:05

cdeszaq


1 Answers

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)
like image 131
svick Avatar answered Nov 16 '22 01:11

svick