0

I try to perform an left outer join within linq. My Datasource is:

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

My query is:

'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)}

What I expect to get is:

Mark   IT
Andy   No Department

But what I get is

Mark   IT

Could anyone tell me, what is wrong with the query? I just cannot see it, even after reading msdn help for it over again, I just cannot find what is wrong.

ruedi
  • 5,365
  • 15
  • 52
  • 88

1 Answers1

2

I cannot reproduce this behavior because when I try to run your code it throws a NullReferenceException.

However, if I change this code:

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

To this code:

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

I get the expected output:

Mark, IT
Andy, No Department

Community
  • 1
  • 1
Bjørn-Roger Kringsjå
  • 9,849
  • 6
  • 36
  • 64