Linq - Top value from each group

前端 未结 6 1807
盖世英雄少女心
盖世英雄少女心 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:34

    This will require you to group by team name then select the max score.

    The only tricky part is getting the corresponding player, but its not too bad. Just select the player with the max score. Of coarse, if its possible for more than one player to have identical scores do this using the First() function as shown below rather than the Single() function.

    var x =
        from t in teams
        group t by t.TeamName into groupedT
        select new
        {
            TeamName = groupedT.Key,
            MaxScore = groupedT.Max(gt => gt.PlayerScore),
            MaxPlayer = groupedT.First(gt2 => gt2.PlayerScore == 
                        groupedT.Max(gt => gt.PlayerScore)).PlayerName
        };
    

    FYI - I did run this code against your data and it worked (after I fixed that one, little data mistake).

提交回复
热议问题