如何按条件获取组的最大对象(整个对象,而不是它的属性)

本文关键字:对象 属性 获取 条件 何按 | 更新日期: 2023-09-27 17:58:39

我想通过某些标准获取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似乎没有重载,让我从 Max() 以外的IGrouping返回Player对象,它依赖于对象来实现IComparable

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

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

如何按条件获取组的最大对象(整个对象,而不是它的属性)

我认为使用ToListOrderBy可以避免使用第三方代码:

IEnumerable<Player> highestPaidPlayers = players.GroupBy(p => p.Position)
    .Select(g => g.ToList().OrderBy(p => p.Salary).Last());

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

表达式语法解决方案:

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。