如何使用LINQ进行分组,然后获取最大组的值

时间:2011-01-26 22:41:22

标签: c# linq

这是我到目前为止所拥有的:

  var bestReason =
   from p in successfulReasons
   group p by p.Reason into g
   select new { Excuse = g.Key, ExcuseCount = g.Count() };

我现在需要做的是返回一个原因,这是最好的原因,确定过去是成功的。

示例数据:

ID,Reason
---------
0,Weather
1,Traffic
2,Illness
3,Weather
4,Traffic
5,Traffic
6,Pirates

应该返回“流量”

如果可能的话,想在一个LINQ语句中完成所有操作。

感谢。

编辑:如果有7次海盗袭击和7次交通事故,我可以返回任何一个(按字母顺序排在第一位)。

3 个答案:

答案 0 :(得分:11)

var bestReason = successfulReasons
    .GroupBy(r => r.Reason)
    .OrderByDescending(grp => grp.Count())
    .First().Key;

答案 1 :(得分:2)

如果我理解你的问题,你可以这样做:

string bestReason =
    (from p in successfulReasons
     orderby p.Reason
     group p by p.Reason into g
     orderby g.Count() descending
     select g.Key).FirstOrDefault();

答案 2 :(得分:1)

 var group = excuses.GroupBy(m => m.Reason)
      .OrderByDescending(m => m.Count())
      .Select(m => m.Key)
      .FirstOrDefault();

产生以下sql语句:

SELECT TOP (1) [t1].[Reason]
FROM (
    SELECT COUNT(*) AS [value], [t0].[Reason]
    From [dbo].[Excuses] As [t0]
    GROUP BY [t0].[Reason]
    ) As [t1]
ORDER BY [t1].[value] DESC

由于这是一个中等复杂的IQueryable表达式,您可以考虑编译它以加快响应时间:

Func<ExcusesDataContext, string> commonResult = CompiledQuery.Compile(
    (ExcusesDataContext c) => c.Excuses.GroupBy(m => m.Reason).OrderByDescending(m => m.Count()).Select(m => m.Key).FirstOrDefault()
);

Console.WriteLine(commonResult(new ExcusesDataContext()));
Console.ReadLine();

您也可以通过存储库调用存储过程并获取您正在寻找的特定值。这将是通往幸福的最快途径,但维持的乐趣最少:

string excuse = this.repo.Excuses.MostCommonFor(ProblemList.BeingLate);