LINQ:从列表中选择项目(分组依据/选择/总和最大!)

编程入门 行业动态 更新时间:2024-10-27 00:28:39
本文介绍了LINQ:从列表中选择项目(分组依据/选择/总和最大!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

让我绕着Linq前进,玩得开心!有人可以帮我查询一下吗?我有一个数据列表:

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.我想按Key.ToUpper()分组2.对于每个组,我都需要Max(Value)&总和(值)3.对于每个组,我要选择条目出现值!=最大值(值) 最终结果应如下所示:

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

谢谢!

更新,实际上我还需要最大"条目中的密钥":

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

推荐答案

:)

var results = from kvp in source group kvp by kvp.Key.ToUpper() into g select new { Group = g, Max = g.Max(kvp => kvp.Value), Total = g.Sum(kvp => kvp.Value) } into ag from x in ag.Group //SelectMany where x.Value != ag.Max //for the update to the question - note: possibly ambiguous let correct = ag.Group.Where(y => y.Value == ag.Max).First().Key select new { Key = x.Key, Max = ag.Max, Total = ag.Total, Correct = correct };

我有点喜欢这个问题,因为所有小部分(很少使用)都需要答案.

I kinda like the question because of all the little parts (some are rarely used) that are required to make the answer.

Max = g.Max(kvp => kvp.Value), Total = g.Sum(kvp => kvp.Value)

在一个组上执行多个聚合非常简单,但是如果您不知道如何的话就很困难.

Performing multiple aggregations on a group is straightforward, yet challenging if you don't know how.

select a into b

此子句采用之前发生的所有事情,并使用目标启动新查询.没有它,我将不得不像这样开始一个新的查询:

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:

var A = ... select a var B = from b in A

请注意, select into 子句将从范围中删除 kvp 和 g .

It's important to note that the select into clause removes kvp and g from scope.

from b in source from a in b.A //SelectMany

此子集合的拆包"将我对b的查询转换为对a的查询.与默认的Enumerable.SelectMany重载不同,它将父级( b )保留在范围内.

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.

where x.Value != ag.Max

将孩子的财产与父母的财产进行比较?愉快.重要的是要记住,即使您刚刚分组(没有 HAVING ),也要在要过滤的任何时间打破 where .

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 no HAVING).

更多推荐

LINQ:从列表中选择项目(分组依据/选择/总和最大!)

本文发布于:2023-10-16 20:27:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498650.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   项目   列表中   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!