鉴于采购订单清单,其中一些已部分发货,其中一些已全部发货,我正在努力编写一个linq到对象查询,按月对订单进行分组并汇总订购金额和发货金额。 / p>
Public Class Order
Property OrderDate as Date
Property Items as List(Of OrderItem)
end Class
Public Class OrderItem
Property Sku as string
Property Qty as integer
Property Price as decimal
Property Shipments as list(Of Shipments)
End Class
Public Class Shipment
Property ShipmentDate as Date
Property OrderItem as OrderItem
Property ShippedQty as integer
end class
Dim Orders as List(Of Order)=GetOrdersFromSomewhere()
Dim Query=Orders.SelectMany(function(x) x.Items).SelectMany(function(y) y.Shipments)
但是,Query仅收集已发送的商品,跳过未发货的商品
答案 0 :(得分:1)
您需要使用 GroupBy ,然后执行 Sum 。
您可以向OrderItem类添加方法, TotalPrice 以获取总价格或订单,同样您可以定义获取AmountShipped价格的方法。在这里,我展示了TotalPrice方法来获得所有订单的总价格。
Public Class OrderItem
Property Sku as string
Property Qty as integer
Property Price as decimal
Property Shipments as list(Of Shipments)
Public Function TotalPrice() As Decimal
Return CDec(Me.Qty) * Me.Price
End Function
End Class
然后,为了按日期对订单进行分组并获得总和,您可以使用以下代码
Dim orders = New GetOrdersFromSomewhere()
Dim ordersGroupedByDate = orders.GroupBy(Function(x) x.OrderDate)
For Each orderByDate As var In ordersGroupedByDate
Dim dateTimeItem = orderByDate.Key
Dim sumOfOrderedItems = orderByDate.SelectMany(Function(x) x.Items.[Select](Function(y) y.TotalPrice())).Sum()
Next
答案 1 :(得分:1)
使用stringformat" yyyy-MM"按月分组订单对于OrderDate
然后计算单独订购和装运的数量
Dim orders As List(Of Order) = GetOrdersFromSomewhere()
Dim result = orders.GroupBy(Function(o) o.OrderDate.ToString("yyyy-MM")).
Select(Function(grp)
Return New With
{
.Month = grp.Key,
.OrderedSum = grp.Sum(Function(o) o.Items.Sum(Function(item) item.Qty)),
.ShippedSum = grp.Sum(Function(o) o.Items.Sum(Function(item) item.Shipments?.Sum(Function(ship) ship.ShippedQty)))
}
End Function)
'Print result
For Each month In result
Console.WriteLine($"{month.Month}{vbTab}Ordered: {month.OrderedSum}, Shipped: {month.ShippedSum}")
Next