Search code examples
linqcountmaxlinq-group

LINQ Group and Count with a Max


Can someone write a LINQ query for the following please

Given the data below I need the following The Player with the highest score each week and the count of them if they win more than one week. If a tie results for the top score in a week then each player gets a count of one. The example data includes this situation

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 

The result will be

Player         Count
Steve            1
John             2
Mark             1
Pete             1

Solution

  • I would probably break this into two steps - which won't actually mean that anything gets executed any earlier, but it's simpler to understand.

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

    The naming is very important here - hopefully by spelling things out I've made it reasonably clear. I'm sure there are other ways of doing it of course, but that's the clearest one I've thought of.