2

有人可以为以下内容编写 LINQ 查询吗

鉴于下面的数据,我需要以下每周得分最高的玩家以及他们获胜超过一周的人数。如果一周内的最高分出现平局,那么每个玩家都会得到一个计数。示例数据包括这种情况

Week   Player         Points 
1      Steve            35 
1      Mark             29 
1      John             26 
2      John             23 
2      Mark             21 
2      Steve            21 
3      Mark             42 
3      John             42 
3      Steve            19 
4      Pete             28 
4      John             16 
4      Steve            14 
4      Mark             12 

结果将是

Player         Count
Steve            1
John             2
Mark             1
Pete             1
4

1 回答 1

5

我可能会将其分为两个步骤 - 这实际上并不意味着任何事情都会更早地执行,但它更容易理解。

// For each week, yield a sequence of winning results
var winningResultsByWeek = from result in results
                           group result by result.Week into week
                           let winningScore = week.Max(x => x.Points)
                           select week.Where(x => x.Points == winningScore)

var winsPerPlayer = from winningResults in winningResultsByWeek
                    from winningResult in winningResults
                    group winningResult by winningResult.Player into winsByPlayer
                    select new { Player = winsByPlayer.Key,
                                 Count = winsByPlayer.Count() };

命名在这里非常重要——希望通过拼写出来我已经相当清楚了。我确信当然还有其他方法可以做到这一点,但这是我想到的最清晰的一种。

于 2013-05-19T19:47:35.543 回答