我有一个列表,上面有一些数据如下。
Player 1
名称- xx
红队
要点- 23
播放器2
名称- xx
绿色团队
要点- 20
播放器3
名称- xx
蓝队
分- 40
播放器4
名称- xx
绿色团队
要点- 20
...and等等。
到目前为止,我只列出了每个球员的名单。很简单。
var item = (from player in playerList.players
orderby player.points descending
select player);
现在,我能做些什么呢?基本上把所有的球员聚集在同一支球队里,把他们所有的积分加在一起,把他们作为一个整体展现出来。所以基本上就像-
红-200
蓝-190
..。
发布于 2016-04-13 20:26:57
您可以使用GroupBy()
将成员按其Team
属性分组,并使用Sum()
方法获取总计:
// Group each player by the Team property and then associate the
// team name to the total points for that team
var teams = playerList.players.GroupBy(p => p.Team)
.Select(t => new { Team = t.Key,Points = t.Sum(p => p.Points)});
// Loop through your teams here
foreach(var team in teams)
{
Console.WriteLine($"{team.Team}: {team.Points}");
}
你可以请参阅此处的交互式示例。
发布于 2016-04-13 20:22:50
您可以使用group By
将球员分组:
var teams = (from player in playerList.players
group player by player.team into team
select new { Team = team.Key, Points = team.Sum(t => t.points) });
或使用扩展方法:
var teams = playerList.players.GroupBy(p => p.team)
.Select(t => new
{
Team = t.Key,
Points = t.Sum(p => p.points)
});
发布于 2016-04-13 20:24:15
GroupBy是你要找的东西:
var result = playerList.players.GroupBy(x=>x.Team)
.Select(grp=> new {
GroupName=grp.Key,
Points=grp.Sum(y=>y.Points));
试试看!
https://stackoverflow.com/questions/36608754
复制相似问题