LINQ:从列表中选择项目(Group By/Select/Sum&Max!)

And*_*ite 9 c# linq select group-by

只是让我的头围绕Linq并享受很多乐趣!任何人都可以帮我查询:
我有一个数据列表:

    Key  Value
    Aaa  12
    AaA  10
    AAa  5
    BBB  2
    Bbb  1
1.我想GROUP BY Key.ToUpper()
2.对于每一个组,我需要马克斯(价值)之和(数值)
3.对于每一个组我想有选择项的值!= MAX(值)
的最终结果应该是这样的:
    Key Max Total
    AaA 12  27
    AAa 12  27
    Bbb 2   3
谢谢!

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

    Key Max Total Correct
    AaA 12  27    Aaa
    AAa 12  27    Aaa
    Bbb 2   3     BBB 

Amy*_*y B 16

:)

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 
  };
Run Code Online (Sandbox Code Playgroud)

我有点像这个问题,因为需要做出答案的所有小部分(有些很少使用).


Max = g.Max(kvp => kvp.Value),
Total = g.Sum(kvp => kvp.Value)
Run Code Online (Sandbox Code Playgroud)

对一个组执行多个聚合很简单,但如果你不知道怎么做,那就很有挑战性.


select a into b
Run Code Online (Sandbox Code Playgroud)

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

var A = ... select a

var B = from b in A
Run Code Online (Sandbox Code Playgroud)

值得注意的是,这是很重要的select into条款删除kvp,并g从范围.


  from b in source
  from a in b.A  //SelectMany
Run Code Online (Sandbox Code Playgroud)

这个子集合的"解包"将我对b的查询转换为关于a的查询.与默认的Enumerable.SelectMany重载不同,它将parent(b)保留在范围内.


where x.Value != ag.Max
Run Code Online (Sandbox Code Playgroud)

将孩子的财产与父母的财产进行比较?愉快.重要的是要记住在where你想要过滤的任何时候爆发,即使你只是分组(没有HAVING).