在LINQ中加入+ Group + Aggregate

时间:2013-07-21 19:06:58

标签: c# linq

我有以下查询,我将其放入DataGrid

var balancePerAccount = from bal in data.balanceDetails
                        join acc in data.userPaymentDetails on bal.userName equals acc.userName
                        where bal.paymentID == 0
                        group bal by bal.userName into g
                        where g.Sum(p => p.rebateBeforeService) >= 20
                        select new
                        {
                            Username = g.Key,
                            Amount = g.Sum(p => p.rebateBeforeService),
                        };
dgPaymentsPending.DataSource = balancePerAccount;
dgPaymentsPending.DataBind();

我想要做的是将acc内的内容添加到select。例如,我想添加PaymentProvider = acc.PaymentProvider。我试着以我能想到的方式翻转它,包括从组中获取First()并尝试从那里访问它,但我似乎无法找到访问它的方法。我可能只是遗漏了一些非常简单的东西,但我一直在寻找谷歌一段时间,我似乎无法找到一个类似的例子。有人有想法吗?

1 个答案:

答案 0 :(得分:3)

使用匿名类型new { bal, acc }扩展分组来源,然后使用First

var balancePerAccount = from bal in data.balanceDetails
                        join acc in data.userPaymentDetails on bal.userName equals acc.userName
                        where bal.paymentID == 0
                        group new { bal, acc } by bal.userName into g
                        where g.Sum(p => p.bal.rebateBeforeService) >= 20
                        select new
                        {
                            Username = g.Key,
                            PaymentProvider = g.FirstOrDefault().acc.PaymentProvider,
                            Amount = g.Sum(p => p.bal.rebateBeforeService),
                        };