我有一个计算比赛结果的web应用程序:
- 参赛者在几个小时内尝试
x
次活动(每个活动分配一个分值)。 - 他们的总分是5个最高分的总和。
我有以下代码在我的控制器。我尝试在几个地方使用.Take(5)
,但它返回前5个分数仅,或表中输入的前5个分数。
分组分为几个领域,参赛者按类别(年龄)和性别获奖。我使用一个名为"游戏"的视图模型。我最近一次失败的代码块:
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)
};
我觉得你快成功了。计算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)
};