问题描述
让我绕着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 entriesThere 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:从列表中选择项目(分组依据/选择/总和最大!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!