次のサンプルコードがあります。
Class Parent
Public Property Id As Integer
Public Property Name As String
End Class
Class Child
Public Property Id As Integer
Public Property ParentId As Integer
Public Property Name As String
End Class
Module Module1
Sub Main()
Dim parent1 As New Parent With {.Id = 1, .Name = "Alvin"}
Dim parent2 As New Parent With {.Id = 2, .Name = "Ben"}
Dim child1 As New Child With {.Id = 100, .ParentId = 1, .Name = "Chester"}
Dim child2 As New Child With {.Id = 101, .ParentId = 1, .Name = "David"}
Dim ParentList As New List(Of Parent)({parent1, parent2})
Dim ChildList As New List(Of Child)({child1, child2})
Dim result = _
From p In ParentList _
Aggregate c In ChildList Where c.ParentId = p.Id _
Into FirstOrDefault() _
Where FirstOrDefault Is Nothing OrElse FirstOrDefault
End Sub
End Module
「結果」に入るLINQクエリは不完全です。なぜなら、そこで何が起こっているのか困惑しているからです。FirstOrDefault は、式のその時点で単一の Child オブジェクトを参照することを期待していますが、子オブジェクトのコレクションを参照しています。なんで?子が関連付けられていない、または特定の条件に一致する子を持つ親のリストを取得する最良の方法は何ですか? (私の実際のコードには最大 1 つの子があるため、このサンプル コードは代表的なものではありません。)
FirstOrDefault のコレクションが何を参照しているのかわかりません。値は常に 1 つだけにするか、何も指定しないでください。