【问题标题】:C# LINQ Query - Group ByC# LINQ 查询 - 分组依据
【发布时间】:2009-01-31 21:08:01
【问题描述】:

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

我有一个 CallLogs 表,我想返回一个结果,该结果代表持续时间最长的呼叫。

该行如下所示:

[ID] [RemoteParty] [持续时间]

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

使用 LINQ,我做到了这一点:

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 的总持续时间,但我需要最大单个结果。

[DistinctRemoteParty1] [持续时间]

[DistinctRemoteParty2] [持续时间]

[DistinctRemotePartyN] [持续时间]

如何修改查询以实现此目的?

【问题讨论】:

    标签: c# .net linq


    【解决方案1】:

    对结果排序并返回第一个。

    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】:

      看看 linq 的“Max”扩展方法

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

      【讨论】:

      • 那只会返回没有 RemoteParty 部分的最大 TotalDuration。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多