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.
Your query doesn't work, because you're trying to apply |
on Foo
s, 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With