LINQ组和最大计数



有人能写一个LINQ查询吗?

给定下面的数据,我需要以下内容每周得分最高的玩家,如果他们赢得超过一个星期,他们的计数。如果在一周内出现平局,那么每个玩家都得1分。示例数据包括以下情况

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

我可能会把它分成两步——这实际上并不意味着任何东西都要提前执行,但这样更容易理解。

// 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() };

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

相关内容

  • 没有找到相关文章

最新更新