我尝试在linq中执行左外连接。我的数据源是:
Public Class Department
Public Property ID As Integer
Public Property Name As String
Public Shared Function GetAllDepartments() As List(Of Department)
Return New List(Of Department) From { _
New Department With {.ID = 1, .Name = "IT"},
New Department With {.ID = 2, .Name = "HR"},
New Department With {.ID = 3, .Name = "Payroll"}
}
End Function
End Class
Public Class Employee
Public Property ID As Integer
Public Property Name As String
Public Property DepartmentID As Integer
Public Shared Function GetAllEmployees() As List(Of Employee)
Return New List(Of Employee) From { _
New Employee With {.ID = 1, .Name = "Mark", .DepartmentID = 1},
New Employee With {.ID = 10, .Name = "Andy"}
}
End Function
End Class
我的查询是:
'Left Outer Join
Dim result = From emp In Employee.GetAllEmployees
Group Join dep In Department.GetAllDepartments
On emp.DepartmentID Equals dep.ID Into eGroup = Group
From all In eGroup.DefaultIfEmpty
Select New With {
.Person = emp.Name,
.DepartmentName = If(all.Name Is Nothing, "No Department", all.Name)}
我期望得到的是:
Mark IT
Andy No Department
但我得到的是
Mark IT
有谁能告诉我,查询有什么问题?我只是看不到它,即使再次阅读msdn帮助之后,我也找不到有什么问题。
答案 0 :(得分:2)
我无法重现此行为,因为当我尝试运行您的代码时会抛出NullReferenceException。
但是,如果我更改此代码:
.DepartmentName = If(all.Name Is Nothing, "No Department", all.Name)}
到此代码:
.DepartmentName = If((all Is Nothing), "No Department", all.Name)}
我得到了预期的输出:
Mark,IT
Andy,No Department