2014-09-07 74 views
0

我尝试在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的帮助文件后,我也无法看到它,我只是无法找到问题所在。

回答

2

我无法重现此行为,因为当我尝试运行您的代码时,它会抛出NullReferenceException

不过,如果我更改此代码:

.DepartmentName = If(all.Name Is Nothing, "No Department", all.Name)} 

要将此代码:

.DepartmentName = If((all Is Nothing), "No Department", all.Name)} 

我得到预期的输出:

马克,IT
安迪,没有部门

+0

+1第一次测试就足够了。 – Steve

+0

谢谢@Steve! :)是的,你说得对,应该就够了。 –

+1

好的。得到它了。非常感谢! – ruedi