1个linq表达式中的多个GroupBy

时间:2014-05-10 01:30:41

标签: c# linq group-by

我似乎无法在1个linq表达式中组合2个GroupBy语句..

现在我正在做这样的事情:

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;
}

我想做的是这样......

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

但那不行。有人可以帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

看起来这就是你想要的,关键点是内部查询包含在Select()的外部调用中:

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

我确实质疑你对LastOrDefault()的使用,因为你没有指定任何排序,你也可以使用FirstOrDefault()并省去跳过最后一个元素的麻烦。