按嵌套表分组

时间:2012-06-15 14:36:25

标签: c# linq entity-framework-4

我有以下表格

[Order]
[Product]
    ProductId
[OrderDetails]
    OrderId
    ProductId
    Quantity

我必须使用Order对象来获取包含按销售额分组的总产品销售额的列表

public class ProductSales 
{
    public decimal Total { get; set; }
    public Product Product { get; set; }
}

鉴于Order对象列表,我如何选择产品详细信息然后按产品分组销售?

我目前的代码如下:

return Orders
       .Select(ordeDetail => new {
           Detail = ordeDetail.OrderDetails
                        .GroupBy(w => new {
                            Detail = w,
                             Product = w.Product})
        .Select (group => new ProductSales {
            Product = group.Key.Product, 
            Quantity = group.Sum(r => r.Quantity)
        })
        .ToList();

1 个答案:

答案 0 :(得分:0)

您可以按产品分组(通过其ID或整行):

return Orders
   .Select(ordeDetail => new {
       Detail = ordeDetail.OrderDetails
                    .GroupBy(w=>w.Product)
                    .Select(w=>new ProductSales {
                       Product=w.Key,
                       Total=w.Sum(prod=>prod.Quantity) })
   })
   .ToList();