Linq分组由多个表组成

时间:2014-01-13 02:41:05

标签: c# linq

我有两个表Orders和OrderDetails,我试图按照订单表中的用户名进行分组,然后在订单详细信息中找到数量的总和

订单表

|Order ID    |Username|
|1           |User 1  |
|2           |User 1  |
|3           |User 2  |

OrderDetails表

|OrderDetailsID| Qty| Order ID|
|1             | 50 |1        |
|2             | 20 |1        |
|3             | 30 |2        | 
|4             | 20 |3        |

如何使用Linq获得按用户分组的总数量?

这就是我想出来的

from order in Entity.Orders
join od in Entity.OrderDetails on order.ID equals od.OrderID
where order.Status != 2
group order by new { order.Username } into users
select new StatsiticsViewClients()
{
     Username = users.Key.Username, 
     Qty = users.SelectMany(x => x.OrderDetails).Sum(x => x.Qty)
}

2 个答案:

答案 0 :(得分:4)

您应该对od进行分组,而不是对order进行分组,因为OrderDetails包含您要尝试求和的属性。

并且您不需要在分组中使用匿名类型,因为您只使用一列进行分组。

from order in Entity.Orders
join od in Entity.OrderDetails on order.ID equals od.OrderID
where order.Status != 2
group od by order.Username into users
select new StatsiticsViewClients()
{
     Username = users.Key, 
     Qty = users.Sum(g => g.Quantity)
}

答案 1 :(得分:2)

分组OrderDetails,然后您可以使用g.Sum(x=> x.Qty)以及组密钥字段中的用户名来获取总和

  from order in Entity.Orders
    join od in Entity.OrderDetails
    on order.ID equals od.OrderID
    where order.Status != 2
    group OrderDetails by order.Username into g
    select new StatsiticsViewClients()
    {
         Username = g.Key.Username, 
         Qty = g.Sum(x=> x.Qty)
    }