【问题标题】:GroupBy and Select syntax optionsGroupBy 和 Select 语法选项
【发布时间】:2012-11-18 12:58:33
【问题描述】:

查看下面的代码,我想按客户 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( ... )

...但无济于事。

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

【问题讨论】:

  • 'var summary = sales.Union(receipts).GroupBy(e => e.id).Select(g => new { g. ..... });'为什么我在IGrouping的成员列表中获取不到查询列,“g”参数?如果我做错了什么?

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


【解决方案1】:

你很接近,尽管我们必须猜测Select( ... ) 包含什么。你可以这样做:

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

【讨论】:

    【解决方案2】:

    试试这个

        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 下生成的查询并优化这些查询。

    【讨论】:

    • 约吉拉吉!它们在您的 salesAndreceipts 查询中是一个逻辑错误,因为 Sales 和 Receipts 表没有 1:N 关系。在您的代码中,它将来自销售的所有特定客户行连接到来自收据的所有特定客户行。这就是我使用 .Union() 加入这两个查询的原因。
    猜你喜欢
    • 2022-08-09
    • 2014-05-06
    • 1970-01-01
    • 2011-08-09
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多