Linq – Top value from each group

My answer is similar to Yuriy’s, but using MaxBy from MoreLINQ, which doesn’t require the comparison to be done by ints:

var query = from player in players
            group player by player.TeamName into team
            select team.MaxBy(p => p.PlayerScore);

foreach (Player player in query)
{
    Console.WriteLine("{0}: {1} ({2})",
        player.TeamName,
        player.PlayerName,
        player.PlayerScore);
}

Note that I’ve changed the type name from “Team” to “Player” as I believe it makes more sense – you don’t start off with a collection of teams, you start off with a collection of players.

Leave a Comment