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;
}
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With