Linq - Top value from each group

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

    The implementation proposed by The Lame Duck is great, but requires two O(n) passes over the grouped set to figure out the Max. It would benefit from calculating MaxScore once and then reusing. This is where SelectMany (the let keyword in C#) comes in handy. Here is the optimized query:

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

提交回复
热议问题