我将使用客户/订单方案来演示我在 VB.NET (4.0) 中要完成的工作。
我想使用LINQ创建以下“CustomerOrders”列表。
考虑以下三个类
Class Customer
Public ID As Integer
Public Name As String
Public Property Orders As New List(Of Order)
End Class
Class Order
Public ID As Integer
Public CustID As Integer
Public ItemID As Integer
Public Qty As Integer
End Class
Class CusomerOrders
Public Property CustID As Integer
Public Property CustName As String
Public Property OrderIJD As Integer
Public Property ItemID As Integer
Public Property Qty As Integer
End Class
我想根据整个客户列表的总订单创建一个新的 CusomerOrders 列表。我可以使用一些嵌套循环来完成此操作。但是,我想知道这是否可以在 LINQ 中完成。
Dim _Customers As New List(Of Customer)
_Customers.Add(New Customer With {.ID = 1, .Name = "John Smith"})
_Customers.Add(New Customer With {.ID = 2, .Name = "Mary White"})
_Customers.Add(New Customer With {.ID = 3, .Name = "Jane Doe"})
_Customers(0).Orders.Add(New Order With {.ID = 567, .CustID = 1, .ItemID = 12345, .Qty = 5})
_Customers(0).Orders.Add(New Order With {.ID = 821, .CustID = 1, .ItemID = 99233, .Qty = 17})
_Customers(0).Orders.Add(New Order With {.ID = 1024, .CustID = 1, .ItemID = 43819, .Qty = 3})
_Customers(1).Orders.Add(New Order With {.ID = 321, .CustID = 2, .ItemID = 34556, .Qty = 12})
_Customers(1).Orders.Add(New Order With {.ID = 901, .CustID = 2, .ItemID = 12345, .Qty = 22})
_Customers(1).Orders.Add(New Order With {.ID = 1530, .CustID = 2, .ItemID = 32145, .Qty = 9})
_Customers(2).Orders.Add(New Order With {.ID = 1214, .CustID = 3, .ItemID = 43556, .Qty = 2})
_Customers(2).Orders.Add(New Order With {.ID = 1239, .CustID = 3, .ItemID = 34560, .Qty = 51})
Dim _CustomerOrders As New List(Of CusomerOrders)
_Customers.ForEach(Sub(_Customer)
_Customer.Orders.ForEach(Sub(_Order)
_CustomerOrders.Add(New CusomerOrders With {.CustID = _Customer.ID,
.CustName = _Customer.Name,
.OrderIJD = _Order.ID,
.ItemID = _Order.ItemID,
.Qty = _Order.Qty})
End Sub)
End Sub)
输出
CustID | CustName | OrderID | ItemID | QTY
--------------------------------------------
1 | John Smith | 567 | 12345 | 5
1 | John Smith | 821 | 99233 | 17
1 | John Smith | 1024 | 43819 | 3
2 | Mary White | 321 | 34556 | 12
2 | Mary White | 901 | 12345 | 22
2 | Mary White | 1530 | 32145 | 9
3 | Jane Doe | 1214 | 43556 | 2
3 | Jane Doe | 1239 | 34560 | 51