代码之家  ›  专栏  ›  技术社区  ›  ChrisF

是否有一个Linq查询可以给出几个最大值的总和?

  •  2
  • ChrisF  · 技术社区  · 14 年前

    我有几个地点的交易数据表,我需要从地点的子集中找出每个地点的最大值之和。想象下表:

    location  year  transactions
      123     2009      57
      124     2009      23
      125     2009      45
      123     2010      64
      124     2010      12
      125     2010      66
    

    因此,如果我只是在查找位置123和124的数据,代码应该选择2010年位置123的值64和2009年位置124的值23。

    我有下面的代码,它找到每个位置的最大值,然后将其添加到运行总数中。

    int total = 0;
    
    foreach (var location in locationIds)
    {
        int? temp = transactions.Where(t => t.Location == location)
                                .Max(t => t.Transactions);
        if (temp.HasValue)
        {
            total += temp.Value;
        }
    }
    

    有没有更优雅的编码方式?

    2 回复  |  直到 14 年前
        1
  •  8
  •   Justin Niessner    14 年前

    var locationsToInclude = new List<int> { 123, 124 };
    
    var sum = transaction
        .Where(t => locationsToInclude.Contains(t.location))
        .GroupBy(t => t.location)
        .Sum(g => g.Max(t => t.transactions));
    
        2
  •  2
  •   Community CDub    7 年前

    Justin's answer

    var sum = transaction
        .GroupBy(x => x.Location)
        .Where(g => locationIds.Contains(g.Key))
        .Sum(g => g.Max(x => x.Transactions));