C#LINQ查询 – 分组依据

我很难理解如何构建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] [持续时间]

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

订购结果并返回第一个结果。

 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(); 

看看linq的“Max”扩展方法

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