我将使用客户/订单场景来演示我在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
答案 0 :(得分:1)
您可以使用SelectMany
方法,这是通过在两个集合上使用From
并按如下方式投影所需的项目来完成的:
Dim query = From c In _Customers
From o In c.Orders
Where c.ID = o.CustID
Select New CusomerOrders With
{
.CustID = c.ID,
.CustName = c.Name,
.OrderIJD = o.ID,
.ItemID = o.ItemID,
.Qty = o.Qty
}
Dim _CustomerOrders = query.ToList()
我更喜欢加入SelectMany
,因为本地查询更快。在这种情况下,加入的挑战是您无法像我上面所做的那样访问c.Orders
。如果您在自己的列表中有订单,那么使用连接就可能更简单。