GroupBy和Select语法选项

时间:2012-11-18 12:58:33

标签: .net linq entity-framework entity-framework-4

请查看下面的代码,我想按客户ID汇总查询结果,并将客户ID列旁边的销售和收据列之和进行分组。

var sales = from s in context.Sales
            select new { id = s.CustomerID, sales = s.Amount, receipts = (decimal)0 };

var receipts = from r in context.Receipts
            select new { id = r.CustomerID, sales = (decimal)0, receipts = r.Amount };

var summary = sales.Union(receipts).ToList();

我尝试使用以下的一些组合来实现相同的目标:

var summary = sales.Union(receipts).GroupBy(e=>e.id).Select( ... )

......但无济于事。

期待获得正确的相关语法。

2 个答案:

答案 0 :(得分:0)

试试这个

    var salesAndreceipts = from data in context.Receipts
                               join data2 in context.Receipts on data.CustomerID on data2.CustomerID
                               select new { id = r.CustomerID, sales = data.Sales, receipts = data2.Amount };

<强>更新 而不是上述内容,请在从销售和收据中获取数据后尝试以下内容:

      var salesAndReceipts = sales.Union(receipts).ToList(); 


        var groupedData = from data in salesAndreceipts
                          group data by new {id=data.CustomerID}
                              into SalesRecepientGroup
                              Select new
                              {
                                  id = SalesRecepientGroup.Key.CustomerID,
                                  sales = SalesRecepientGroup.Sum(x=>x.Sales),
                                  receipts = SalesRecepientGroup.Sum(x=>x.Amount)

                              };

希望这会有所帮助.. :)

更新

然后,您可以检查它在EFProfiler下生成的查询并优化这些查询。

答案 1 :(得分:0)

你很接近,虽然我们必须猜测Select( ... )包含的内容。你可以这样做:

summary
    .GroupBy(s => s.id)
    .Select(g => new { id = g.Key,
                       salesSum = g.Sum(x => x.sales), 
                       receiptsSum = g.Sum(x => x.receipts)
                     })