Reputation: 61
In the query below I do calculate the combined value of all football teams within league 1. The solution I've came up with, though it works, seems rather bulky.
I would like to find a better approach i.e. a one lined linq query like so:
footballteams.Where(x => x.League == 1).Sum(x => x.Networth);
My current code:
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;
}
}
Upvotes: 5
Views: 1412
Reputation: 519
totalWealth = footballTeams
.Where(x => x.League == 1)
.Select(
x => x.Select(
y => y.networth
).Sum()
)
.Sum();
If you want you can make it one line, but you will notice that readability is crucial for productive coding.
Upvotes: 4
Reputation: 56489
Use SelectMany then Sum
.
var totalWealth = footballTeams.Where(x => x.League == 1)
.SelectMany(x => x.Select(e => e.networth))
.Sum();
SelectMany()
Exceprt:
Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.
Upvotes: 11
Reputation: 32072
You can do it all in a single statement:
var totalWorth = context.FootballTeam
.GetQueryable()
.Where(x => x.League == 1)
.GroupBy(x => x.TeamName)
.Sum(x => x.Sum(y => y.NetWorth));
You also skip the enumeration performed by the two ToList()
calls with this.
Upvotes: 4