如何编写结合 group by 和聚合的 LINQ 查询?
给定以下输入,如何编写 LINQ 查询或表达式来返回数量的聚合结果集?
输入:
var foo = new[] { new { PO = "1", Line = 2, QTY = 0.5000 },
new { PO = "1", Line = 2, QTY = 0.2500 },
new { PO = "1", Line = 2, QTY = 0.1000 },
new { PO = "1", Line = 2, QTY = -0.1000 }
}.ToList();
期望的结果:
类似于
new { PO = "1", Line = 2, QTY = 0.7500 } // .5 + .25 + .1 + -.1
我如何为多行编写它(请参阅 foo 中的对象模型)?
Given the following input, how do I write a LINQ query or expression to return an aggregated result set for the quantity?
Input:
var foo = new[] { new { PO = "1", Line = 2, QTY = 0.5000 },
new { PO = "1", Line = 2, QTY = 0.2500 },
new { PO = "1", Line = 2, QTY = 0.1000 },
new { PO = "1", Line = 2, QTY = -0.1000 }
}.ToList();
Desired result:
Something along the lines of
new { PO = "1", Line = 2, QTY = 0.7500 } // .5 + .25 + .1 + -.1
How would I write it for multiple lines as well (see the object model in foo)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样:
如果你只有一行,只需添加一个
.Single()
-result
是一个匿名类型的IEnumerable
在设置foo
时定义。编辑:
如果 PO 和线路都应指定不同的组(PO 可以具有不同的值),则它们都必须是组键的一部分:
How about this:
In the case you just have one Line, just add a
.Single()
-result
is anIEnumerable
of the anonymous type defined when you set upfoo
.Edit:
If both PO and Line should designate different groups (PO can have different values), they both have to be part of the group key: