使用C#在Linq to SQL中查找大多数事件

时间:2013-09-04 13:42:23

标签: asp.net c#-4.0 linq-to-sql

我有以下查询获取Name和TotalPoints,如下所示:

var gradeData = (from data in oAngieCtxt.prc_ShopInstanceCustomersData(Convert.ToInt32(this.ShopInstanceID), 10000, false)
                         .Where(row => row.RecievedPoints != "n/a")
                        .GroupBy(row => new { row.Name })
                        .Select(g => new
                        {
                            TotalPoints = g.Sum(x => Convert.ToDouble(x.RecievedPoints) * (x.Weightage.ToString() == "0.00" ? 1 : Convert.ToDouble(x.Weightage))),
                            Name = g.Key.Name
                        })
                         select data).ToList();

我将获得如下数据:

TotalPoints        Name
  5                  A
  10                 B
  5                  C
  15                 D
  5                  E

如果我们观察上面的列表5是最常见的。我必须从“gradeData”中获取该值。

我怎么能得到它?

2 个答案:

答案 0 :(得分:6)

var mostCommon = gradeData.GroupBy(x => x.TotalPoints)
    .OrderByDescending(g => g.Count())
    .Select(g => g.Key)
    .First();

答案 1 :(得分:2)

下面的查询为您提供了最常见的一点及其所有相关名称:

var result = gradeData.GroupBy(x => x.TotalPoints)
                      .OrderByDescending(x => x.Count())
                      .Select(g => new
                          {
                              TotalPoints = g.Key,
                              Names = g.Select(x => x.Name).ToList()
                          })
                      .First();