Skip to content

Left outer join method syntax throws a null reference exception - join operators documentation #46938

@valentincpopa

Description

@valentincpopa

Type of issue

Code doesn't work

Description

the following code throws a null reference exception if the department to which a student is assigned to does not exist:

var query = students
    .GroupJoin(
        departments,
        student => student.DepartmentID,
        department => department.ID,
        (student, departmentList) => new { student, subgroup = departmentList })
    .SelectMany(
        joinedSet => joinedSet.subgroup.DefaultIfEmpty(),
        (student, department) => new
        {
            student.student.FirstName,
            student.student.LastName,
            Department = department.Name
        });

foreach (var v in query)
{
    Console.WriteLine($"{v.FirstName:-15} {v.LastName:-15}: {v.Department}");
}

we can solve this by using the null conditional operator and the null-coalescing operator similarly to what is presented in the query syntax:

...
{
    student.student.FirstName,
    student.student.LastName,
    Department = department?.Name ?? string.Empty
});
...

Page URL

https://learn.microsoft.com/en-us/dotnet/csharp/linq/standard-query-operators/join-operations

Content source URL

https://github.com/dotnet/docs/blob/main/docs/csharp/linq/standard-query-operators/join-operations.md

Document Version Independent Id

95b5cc6b-9612-6380-5dd4-b2efaac40732

Platform Id

97b3d8d9-46b9-4ca9-a14b-2d816a35f9bc

Article author

@BillWagner

Metadata

  • ID: 2ebd6c45-3cfb-ba5f-5d78-4728a948b598
  • PlatformId: 97b3d8d9-46b9-4ca9-a14b-2d816a35f9bc
  • Service: dotnet-csharp
  • Sub-service: csharp-linq

Related Issues

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions