gpt4 book ai didi

c# - Linq - 每个组的最高值

转载 作者:IT王子 更新时间:2023-10-29 04:01:03 25 4
gpt4 key购买 nike

我如何使用 Linq 从每个组中选择最高值

当我有这样的代码段时:

var teams = new Team[]
{
new Team{PlayerName="Ricky",TeamName="Australia", PlayerScore=234},
new Team{PlayerName="Hussy",TeamName="Australia", PlayerScore=134},
new Team{PlayerName="Clark",TeamName="Australia", PlayerScore=334},

new Team{PlayerName="Sankakara",TeamName="SriLanka", PlayerScore=34},
new Team{PlayerName="Udana",TeamName="SriLanka", PlayerScore=56},
new Team{PlayerName="Jayasurya",TeamName="SriLanka", PlayerScore=433},

new Team{PlayerName="Flintop",TeamName="England", PlayerScore=111},
new Team{PlayerName="Hamirson",TeamName="England", PlayerScore=13},
new Team{PlayerName="Colingwood",TeamName="England", PlayerScore=421}
};

期望的结果:

Team Name         Player Name     ScoreSrilanka          Jayasurya        433England           colingwood       421Australia         Clark            334 

最佳答案

我的回答与 Yuriy 的类似,但使用了 MaxBy来自 MoreLINQ ,不需要通过整数进行比较:

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);
}

请注意,我已将类型名称从“Team”更改为“Player”,因为我认为这更有意义 - 你不是从一组团队开始,而是从一组球员开始。

关于c# - Linq - 每个组的最高值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1575316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com