5

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;
    }
}
1
  • 1
    Why group and then ungroup to get the sum of the networth? Wouldn't it make more sense to get the teams as a List<FootballTeam>, then from this list you can group or you can sum, whichever you like? Also, how can you run .Where(x => x.League == 1) on an IGrouping? Those objects don't have a .League property. Commented Jun 5, 2018 at 21:57

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

4
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.

4 Comments

this will not compile. Due to the second Select. TO make it compile the first Select should be SelectMany
@CodeNotFound I think they meant to do .Select(x => x.Select(y => y.networth).Sum()).Sum();. With the current example, seems like there is a typo y.networth.Sum() from the author.
@CodeNotFound with the edit, it should now work. Also, note that SelectMany is only required if you want to collapse nested sequences, the inner Select in the answer returns a scalar value so SelectMany is not required here. But yes one could also do it with SelectMany as in my answer :).
great . You're right. SelectManay not needed with this version :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.