gpt4 book ai didi

c# - 用 Linq 替换嵌套循环

转载 作者:太空狗 更新时间:2023-10-29 23:58:46 25 4
gpt4 key购买 nike

在下面的查询中,我确实计算了联赛 1 中所有足球队的总值(value)。我提出的解决方案虽然有效,但看起来相当庞大。

我想找到一种更好的方法,即像这样的单行 linq 查询:

footballteams.Where(x => x.League == 1).Sum(x => x.Networth);

我当前的代码:

List<IGrouping<int, FootballTeam>> footballTeams = context.FootballTeam
.GetQueryable()
.GroupBy(x => x.TeamName)
.ToList();

var prem = footballTeams.Where(x => x.League == 1).ToList();
var totalWealth = 0;

foreach (var team in prem)
{
foreach(var singleteam in team)
{
totalWealth = totalWealth + singleteam.networth;
}
}

最佳答案

使用SelectMany然后 Sum

var totalWealth = footballTeams.Where(x => x.League == 1)
.SelectMany(x => x.Select(e => e.networth))
.Sum();

SelectMany() 摘录:

Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.

关于c# - 用 Linq 替换嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50709242/

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