Pregunta

I cannot seem to combine 2 GroupBy statements in 1 linq expression..

For now i'm doing something like this:

double maxInvestment = 0;

foreach (var playerAction in TotalUserActions.GroupBy(p => p.Player))
{
    var MaxInvestmentPerPlayer = playerAction.GroupBy(p => p.RoundId)
                                             .Select(p => p.LastOrDefault())
                                             .Sum(p=> p.BetSize);

    if(MaxInvestmentPerPlayer > maxInvestment)
        maxInvestment = MaxInvestmentPerPlayer;
}

What I would like to do is something like this...

double maxInvestment = TotalUserActions.GroupBy(p => p.Player)
                                       .GroupBy(p => p.RoundId)
                                       .Select(p => p.LastOrDefault())
                                       .Sum(p=> p.BetSize);

But that wont work.. Can someone help me on this?

Thanks!

¿Fue útil?

Solución

Looks like this is what you want, the key takeaway being the inner query is wrapped in an outer call to Select():

var maxInvestment = TotalUserActions.GroupBy(p => p.Player)
                                    .Select(g => g.GroupBy(x => x.RoundId)
                                                  .Select(x => x.LastOrDefault())
                                                  .Sum(x => x.BetSize))
                                    .Max();

I do question your use of LastOrDefault() though as, since you have not specified any ordering, you may as well use FirstOrDefault() and save the hassle of skipping to the last element.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top