문제

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!

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top