LINQ:从列表中选择项目(分组/选择/求和与最大值!)
我只是沉浸在 Linq 中并享受很多乐趣!任何人都可以帮我解决这个问题吗:
我有一个数据列表:
Key Value Aaa 12 AaA 10 AAa 5 BBB 2 Bbb 11. I want to group by Key.ToUpper()
2. For every group I need the Max(Value) & Sum(Value)
3. For every group I want to select the entries There the Value != Max(value)
the final result should be like this:
Key Max Total AaA 12 27 AAa 12 27 Bbb 2 3Thanks!
更新,实际上我还需要最大条目中的密钥:
Key Max Total Correct AaA 12 27 Aaa AAa 12 27 Aaa Bbb 2 3 BBB
Just getting my head around Linq and having lots of fun! Can any one aid me with a query for this:
I have a list of data:
Key Value Aaa 12 AaA 10 AAa 5 BBB 2 Bbb 1
1. I want to group by Key.ToUpper()
2. For every group I need the Max(Value) & Sum(Value)
3. For every group I want to select the entries
There the Value != Max(value)
the final result should be like this:
Key Max Total AaA 12 27 AAa 12 27 Bbb 2 3
Thanks!
Update, actually I also need the Key from the Maximum entry:
Key Max Total Correct AaA 12 27 Aaa AAa 12 27 Aaa Bbb 2 3 BBB
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
:)
我有点喜欢这个问题,因为做出答案所需的所有小部分(有些很少使用)。
对一个组执行多个聚合很简单,但如果您不知道如何操作,则具有挑战性。
该子句获取之前发生的所有内容并开始使用目标的新查询。如果没有它,我就必须开始一个像这样的新查询:
重要的是要注意
select into
子句从中删除了kvp
和g
范围。子集合的这种“解包”将我对 b 的查询变成了对 a 的查询。与默认的 Enumerable.SelectMany 重载不同,它将父级 (
b
) 保留在范围内。将孩子的财产与父母的财产进行比较?愉快。重要的是要记住在任何想要过滤的时候都要打破
where
,即使你只是分组(没有HAVING
)。:)
I kinda like the question because of all the little parts (some are rarely used) that are required to make the answer.
Performing multiple aggregations on a group is straightforward, yet challenging if you don't know how.
This clause takes everything that happened before and starts a new query with the target. Without it, I'd have to start a new query like this:
It's important to note that the
select into
clause removeskvp
andg
from scope.This "unpacking" of the child collection turns my query about b's into a query about a's. Unlike the default Enumerable.SelectMany overload, it leaves the parent (
b
) in scope.Comparing a child's property with a parent's property? Delightful. It's important to remember to break out
where
anytime you want to filter, even if you just grouped (there is noHAVING
).