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

C#LINQ查询-分组依据

  •  28
  • martin  · 技术社区  · 17 年前

    我很难理解如何形成LINQ查询来执行以下操作:

    我有一个CallLogs表,我想返回一个结果,它表示持续时间最长的调用。

    行如下所示:

    同一个RemoteParty可以有多行,每行代表一个特定持续时间的调用。我想知道哪一个聚会的总持续时间最长。

    var callStats = (from c in database.CallLogs
                     group c by c.RemoteParty into d
                     select new
                     {
                          RemoteParty = d.Key,
                          TotalDuration = d.Sum(x => x.Duration)
                     });
    

    所以现在我有了一个分组结果,其中包含每个RemoteParty的总持续时间,但我需要最大单个结果。

    [DistinctRemoteParty2][持续时间]

    [持续时间]

    2 回复  |  直到 6 年前
        1
  •  26
  •   tvanfosson    17 年前

    var callStats = (from c in database.CallLogs
                     group c by c.RemoteParty into d
                     select new
                     {
                          RemoteParty = d.Key,
                          TotalDuration = d.Sum(x => x.Duration)
                     });
    
    callStats = callStats.OrderByDescending( a => a.TotalDuration )
                         .FirstOrDefault();
    
        2
  •  4
  •   flq    17 年前

    看看linq中的“Max”扩展方法

    callStats.Max(g=>g.TotalDuration);