用Linq替换嵌套循环

J.D*_*Doe 4 c# linq

在下面的查询中,我确实计算了联盟1中所有足球队的总和值.我想出的解决方案虽然有效,但看起来相当笨重.

我想找到一个更好的方法,即一个内衬的linq查询,如下所示:

footballteams.Where(x => x.League == 1).Sum(x => x.Networth);
Run Code Online (Sandbox Code Playgroud)

我目前的代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ous*_* D. 10

然后使用SelectManySum.

var totalWealth = footballTeams.Where(x => x.League == 1)
                               .SelectMany(x => x.Select(e => e.networth))
                               .Sum();
Run Code Online (Sandbox Code Playgroud)

SelectMany() Exceprt:

将序列的每个元素投影到IEnumerable,并将生成的序列展平为一个序列.


SO *_*ood 4

您可以通过一条语句完成这一切:

var totalWorth = context.FootballTeam
    .GetQueryable()
    .Where(x => x.League == 1)
    .GroupBy(x => x.TeamName)
    .Sum(x => x.Sum(y => y.NetWorth));
Run Code Online (Sandbox Code Playgroud)

您还可以使用此跳过两个调用执行的枚举ToList()