-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Closed
Description
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
Document Version Independent Id
95b5cc6b-9612-6380-5dd4-b2efaac40732
Platform Id
97b3d8d9-46b9-4ca9-a14b-2d816a35f9bc
Article author
Metadata
- ID: 2ebd6c45-3cfb-ba5f-5d78-4728a948b598
- PlatformId: 97b3d8d9-46b9-4ca9-a14b-2d816a35f9bc
- Service: dotnet-csharp
- Sub-service: csharp-linq