顧客/注文のシナリオを使用して、VB.NET (4.0) で達成しようとしていることを示します。
LINQを使用して次の「CustomerOrders」リストを作成したいと思います。
次の 3 つのクラスを検討してください。
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
顧客リスト全体の合計注文に基づいて、CustomerOrders の新しいリストを作成したいと考えています。これは、ネストされたループを使用して実現できます。しかし、これが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