ASP.net Linq同时对SQL进行分组和添加?

时间:2012-08-01 14:05:55

标签: c# asp.net linq linq-to-sql

我有一张产品表

产品:

ProdID  | ProdName
     1  | shirt
     2  | pants

尺寸表:

SizeID | Size
     1 | small
     2 | med
     3 | large

订单表

OrderID   | ProdID    |  SizeID    | Qty
 1        |    1      |   1        |  4
 2        |    1      |   1        |  3
 3        |    1      |   2        |  2
 4        |    2      |   1        |  1
 5        |    2      |   3        |  1

我如何得到这样的结果:

ProdName | Size    | Total qty ordered   (group by product and size add all quantities)
   shirt | small   |   7
   shirt | med     |   2
   pants | small   |   1
   pants | large   |   1

谢谢

1 个答案:

答案 0 :(得分:5)

from o in dc.Orders
group o by new { o.Product.ProdName, o.Size.Size } into g
select new { g.Key.ProdName, g.Key.Size, Total = g.Sum(or => or.Qty))};