3

根据某些标准,我想获得 a 的最大对象IGrouping,但是到目前为止,我似乎找不到允许我返回组内的整个对象的重载

List<Player> players = new List<Player>() 
{ 
     new Player() { Name = "Peyton Manning", Age = 36, Position = "QB", Salary = 19000000 },
     new Player() { Name = "Tom Brady", Age = 35, Position = "QB", Salary = 18400000 },
     new Player() { Name = "Drew Brees", Age = 34, Position = "QB", Salary = 21000000 },
     new Player() { Name = "Randy Moss", Age = 35, Position = "WR", Salary = 7000000 },
     new Player() { Name = "Marvin Harrison", Age = 38, Position = "WR", Salary = 11000000 },
     new Player() { Name = "Demaryius Thomas", Age = 23, Position = "WR", Salary = 5000000 },
     new Player() { Name = "Ryan Clady", Age = 26, Position = "OT", Salary = 10000000 },
};

我想编写一个返回结果集的查询,我可以像这样枚举它:

foreach(Player player in highestPaidPlayers) 
{
      Console.WriteLine("The highest paid {0} is {1}, who is being paid {2}", player.Position, player.Name, player.Salary);
}

到目前为止,这是我得到的:

var playersGroupedByPosition = players
    .GroupBy(p => p.Position)
    .Select(g => g.Max(p => p.Salary));

但这只会给我一个最高薪水的列表(例如整数列表)。似乎没有重载,因为Max它让我Player从一个IGrouping以外的对象返回一个对象Max(),它依赖于一个对象来实现IComparable

我的 LINQ 有点弱,所以我还没有想出如何编写子查询来获取组的最大条目并将其返回给外部选择,但是有没有更直接的方法来做到这一点?

我已经看到使用第三方库MoreLINQ(及其自定义运算符MaxBy)引用的解决方案,但我不想走那条路(还),除非不可能使用现有的查询运算符集 - 如果不是,我想了解现有运算符的限制,阻止在查询中完成此操作。

4

2 回答 2

4

我认为你ToList可以避免OrderBy使用第三方代码:

IEnumerable<Player> highestPaidPlayers = players.GroupBy(p => p.Position)
    .Select(g => g.ToList().OrderBy(p => p.Salary).Last());
于 2013-02-10T17:46:45.943 回答
2

使用嵌套“子选择”的解决方案

表达式语法解决方案:

var highestPaidPlayers = players.GroupBy(p => p.Position)
                                 .Select(x => x.Where(p => p.Salary == x.Max(m => m.Salary)).First());

查询语法解决方案:

var highestPaidPlayers = from pl in players
                         group pl by pl.Position
                         into g
                             let max = g.Max(x => x.Salary)
                             let maxPl = g.Where(x => x.Salary == max).First()
                             select maxPl;

试试Ideone

于 2013-02-10T22:20:45.037 回答