我有以下示例代码:
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 在表达式中引用单个子对象,但它引用子对象的集合。为什么?获取没有相关子女或有符合特定条件的孩子的父母名单的最佳方法是什么?(我的实际代码最多只有一个孩子,所以这个示例代码不具有代表性。)
我只是不明白 FirstOrDefault 的集合可能指的是什么。它应该始终只有 1 个值或什么都没有。