c# - Linq 分组依据并与多个表求和

标签 c# linq

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

订单表

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

订单明细表

|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)
}

最佳答案

您应该对 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)
}

关于c# - Linq 分组依据并与多个表求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21083060/

相关文章:

c# - 在 LinqToSql 中是否有更短的方法将属性解析为 Int(或任何其他原语)

c# - 我需要一个 Linq IEnumerable<>.Cast(typeof(T))

c# - IDevTools 实例不包含 CreateDevToolsSession 方法

c# - CSS - 在单个 DIV 中并排放置元素,对齐

c# - Combobox SelectedValue 返回 System.Data.DataRowView 甚至转换为字符串

LINQ 选择第一行

c# - 在 Windows 服务中托管 ASP.NET 5 Web 应用程序

c# - 我可以在一个解决方案中的其他项目中使用主项目中的类和控件吗?

c# - 从 IEnumerable<ObservableCollection<T>> C# 中提取项目

c# - Linq XML 查询属性中具有特定值的父级的后代