我有一个这样的代码:
string[] teamNames = teams.Select(x => x.Name).ToArray();
List<int> wins = new List<int>();
foreach(var _team in teamNames)
{
wins.Add(matches.Count(x =>
((x.Team1 == _team && x.Maps.Count(map => map.Score1 > map.Score2) > x.Maps.Count(map => map.Score2 > map.Score1)) ||
(x.Team2 == _team && x.Maps.Count(map => map.Score2 > map.Score1) > x.Maps.Count(map => map.Score1 > map.Score2))
)));
}
我想知道你是否可以在没有foreach的情况下计算每个球队的胜利,因为foreach只是一个接一个地显示球队的名字。有什么想法吗/
您应该能够通过用Select
替换foreach
来做到这一点:
var wins = teamNames
.Select(_team =>
matches.Count(x =>
((x.Team1 == _team && x.Maps.Count(map => map.Score1 > map.Score2) > x.Maps.Count(map => map.Score2 > map.Score1)) ||
(x.Team2 == _team && x.Maps.Count(map => map.Score2 > map.Score1) > x.Maps.Count(map => map.Score1 > map.Score2))
))
)
.ToArray();
您也可以直接在比赛中使用groupby,而不需要创建teamNames。