如何使用 LINQ 和 lambda 对列表中对象的位标志枚举属性执行按位或运算?
我有一个对象集合,每个对象都有一个位字段枚举属性。我想要得到的是整个集合中位字段属性的逻辑或。我怎样才能在不循环集合的情况下做到这一点(希望使用 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
将成为可行的路线,因为它简单且不复杂,但这只是我实际使用的内容的简化版本。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的查询不起作用,因为您尝试在
Foo
上应用|
,而不是在Attributes
上。您需要做的是获取集合中每个Foo
的MyAttributes
,这正是Select()
所做的:Your query doesn't work, because you're trying to apply
|
onFoo
s, not onAttributes
. What you need to do is to getMyAttributes
for eachFoo
in the collection, which is exaclty whatSelect()
does:首先,您需要将
MyAttributes
公开,否则您无法从Baz
访问它。然后,我认为您正在寻找的代码是:
First, you’ll need to make
MyAttributes
public, otherwise you can’t access it fromBaz
.Then, I think the code you’re looking for is: