Linq - Top value from each group

前端 未结 6 1804
盖世英雄少女心
盖世英雄少女心 2020-12-03 01:10

How can I employ Linq to select Top value from each group

when I have a code segment like :

var teams = new Team[]
 { 
  new Team{PlayerName=\"Ricky\         


        
6条回答
  •  隐瞒了意图╮
    2020-12-03 01:27

    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.

提交回复
热议问题