按组排序

时间:2014-03-21 05:44:20

标签: c# linq

我有一个用于计算比赛结果的网络应用程序:

  1. 竞争对手在几个小时内尝试x次活动(每项活动都会分配一个分值)。
  2. 他们的总分是5个最高分值的总和。
  3. 我的控制器中有以下代码。我尝试在多个地方使用.Take(5),但它只返回前5个分数,或表格中输入的前5个

    分组涉及多个领域,竞争对手按类别(年龄)和性别分类获奖。我正在使用名为“Game”的视图模型。我最近的不成功代码块:

    var compdata = from result in db.Results
                   where result.Complete == true
                   orderby result.Activity.Value descending
                   group result by new
                   {
                       result.CompetitorId,
                       result.Competitor.Name,
                       result.Competitor.Category,
                       result.Competitor.Gender,
                   }
                   into resultsGroup
                   select new Game
                   {
                       CompetitorId = resultsGroup.Key.CompetitorId,
                       Name = resultsGroup.Key.Name,
                       Category = resultsGroup.Key.Category,
                       Gender = resultsGroup.Key.Gender,
                       Score = resultsGroup.Sum(s => s.Activity.Value)
                   };
    

1 个答案:

答案 0 :(得分:0)

我认为你几乎就在那里。在计算Score值时,您需要在分组后执行Take(5) ...以下不是最简洁的方法,但它根据您现在拥有的内容证明了这一点:

Score = resultsGroup.OrderByDescending(s => s.Activity.Value).Take(5).Sum(s => s.Activity.Value)

所以这给出了类似的东西:

var compdata = from result in db.Results
               where result.Complete == true
               group result by new
               {
                   result.CompetitorId,
                   result.Competitor.Name,
                   result.Competitor.Category,
                   result.Competitor.Gender,
               }
               into resultsGroup
               select new Game
               {
                   CompetitorId = resultsGroup.Key.CompetitorId,
                   Name = resultsGroup.Key.Name,
                   Category = resultsGroup.Key.Category,
                   Gender = resultsGroup.Key.Gender,
                   Score = resultsGroup.OrderByDescending(s => s.Activity.Value).Take(5).Sum(s => s.Activity.Value)
               };