C# LINQ 查询 - 分组依据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/499578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:46:31  来源:igfitidea点击:

C# LINQ Query - Group By

c#.netlinq

提问by

I'm having a hard time understanding how I can form a LINQ query to do the following:

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

I have a table CallLogs and I want to get back a single result which represents the call that has the longest duration.

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

The row looks like this:

该行如下所示:

[ID] [RemoteParty] [Duration]

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

There can be multiple rows for the same RemoteParty, each which represents a call of a particular duration. I'm wanting to know which RemoteParty has the longest total duration.

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

Using LINQ, I got this far:

使用 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)
                 });

So now I have a grouped result with the total duration for each RemoteParty but I need the maximum single result.

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

[DistinctRemoteParty1] [Duration]

[DistinctRemoteParty2] [Duration]

[DistinctRemotePartyN] [Duration]

[DistinctRemoteParty1] [持续时间]

[DistinctRemoteParty2] [持续时间]

[DistinctRemotePartyN] [持续时间]

How can I modify the query to achieve this?

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

回答by tvanfosson

Order the result and return the first one.

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

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

回答by flq

Have a look at the "Max" extension method from linq

看看 linq 的“Max”扩展方法

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