LINQ 将列的总和添加到列表条目
Posted
技术标签:
【中文标题】LINQ 将列的总和添加到列表条目【英文标题】:LINQ add sum of columns to list entry 【发布时间】:2021-07-16 10:33:59 【问题描述】:我目前正在开发一个 .net 5.0 应用程序。
我需要使用 LINQ 来做一个复杂的查询:
给出的是List<Player>
我需要转换List<Player>
,但保留所有条目
将每支球队的 TotalScore 添加到“SerieA”中的所有球员
不幸的是,我不知道如何使用 C# LINQ 扩展方法语法正确计算联盟中所有球员的每支球队的 TotalScore。
播放器类:public class Player
public string Name get; set;
public string Team get; set;
public int Score get; set;
public string League get; set;
public int TotalTeamScore get; set;
程序类
public class Program
public static void Main()
// given is a List<Player> - I need to calculate the TotalScore for each team ONLY for Leage "SerieA"
var players = new List<Player>
new Player Name = "Alex", Team = "A", Score = 10, League = "SerieA", TotalTeamScore = 0 ,
new Player Name = "Anna", Team = "A", Score = 20, League = "SerieA", TotalTeamScore = 0 ,
new Player Name = "Berta", Team = "B", Score = 60, League = "SerieA", TotalTeamScore = 0 ,
new Player Name = "Benny", Team = "B", Score = 40, League = "SerieA", TotalTeamScore = 0 ,
new Player Name = "Charlie", Team = "C", Score = 40, League = "PremierLeague", TotalTeamScore = 0 ,
new Player Name = "Connor", Team = "C", Score = 40, League = "PremierLeague", TotalTeamScore = 0 ,
;
// I need to find a proper way to calculate the TotalTeamScore for each Team in league SerieA and add this score to the players...
var teamTotalScores = players
.Where(p => p.League == "SerieA")
.GroupBy(p => p.Team)
.Select(p => new Player
TotalTeamScore = p.Sum(s => s.Score)
// Score = x.Key ??
)
.ToList();
// desired result: same List<Player> - only the Total TeamScore of a Team in "SerieA" should be calculated for each team and added to each player in a team:
// new Player Name = "Alex", Team = "A", Score = 10, League = "SerieA", TotalTeamScore = 30 ,
// new Player Name = "Anna", Team = "A", Score = 20, League = "SerieA", TotalTeamScore = 30 ,
// new Player Name = "Luke", Team = "B", Score = 60, League = "SerieA", TotalTeamScore = 100 ,
// new Player Name = "Lucy", Team = "B", Score = 40, League = "SerieA", TotalTeamScore = 100 ,
// new Player Name = "Charlie", Team = "C", Score = 40, League = "PremierLeague", TotalTeamScore = 0 ,
// new Player Name = "Connor", Team = "C", Score = 40, League = "PremierLeague", TotalTeamScore = 0 ,
你知道如何解决这个问题吗?
您知道如何使用 C# LINQ 扩展方法语法正确计算联盟中所有球员的每支球队的 TotalScore。
【问题讨论】:
【参考方案1】:LINQ 专为查询而设计,而您需要修改集合中的对象。
虽然您可以使用 Enumerable.Select
执行此操作,但标准的 foreach
循环会更合适:
var serieAPlayers = players.Where(p => p.League == "SerieA");
var teamScores = serieAPlayers
.GroupBy(p => p.Team)
.ToDictionary(grp => grp.Key, grp => grp.Sum(p => p.Score));
foreach (var player in serieAPlayers) player.TotalTeamScore = teamScores[player.Team];
【讨论】:
谢谢,效果很好!!也许有一点改进,我必须检查字典中是否存在键 [player.Team]。 :) 啊,是的,foreach
应该只迭代意甲的球员;我会更新答案。以上是关于LINQ 将列的总和添加到列表条目的主要内容,如果未能解决你的问题,请参考以下文章
将列添加到包含其他列值列表的 pandas DataFrame
为啥我不能使用引用 SQL 中其他列的 checkConstraint 将列添加到现有表
编写一个 sql 查询以使用另一列的子字符串将列添加到数据框