LINQ might get a "left join" operator in .net 10

12/9/2024
2 minute read

LINQ has a Join operator, that basically translates to something like a SQL INNER JOIN. There is no built in operator for a LEFT JOIN in LINQ, but you can achieve the same result by using a combination of GroupJoin, SelectMany and DefaultIfEmpty. But there is a chance that this might change in the future, as there is a proposal to add a LeftJoin operator in .net 10.

Now in your every day life, this might not be a big deal, but when it comes to Entity Framework and LINQ to SQL, this can be a nice addition.

How to do LEFT JOINs with LINQ

This is how you would do a LEFT JOIN in LINQ:

var query =
    from t1 in _dbContext.Table1
    join t2 in _dbContext.Table2 on t2.Id equals t1.T2Id into joinedGroup
    from joined in joinedGroup.DefaultIfEmpty()

Or if you are using the method syntax:

var query =
    _dbContext.Table1
        .GroupJoin(_dbContext.Table2, t1 => t1.T2Id, t2 => t2.Id, (t1, t2) => new { t1, t2 })
        .SelectMany(t => t.t2.DefaultIfEmpty(), (t, t2) => new { t1 = @t.t1, t2 });

Be aware, if you want to join on multiple columns, you have to name the properties the same with the same data type. Read more: "LINQ Joins on multiple columns in Entity Framework".

The proposal

The proposal on GitHub by no less than @roji itself, would add the LeftJoin operator as a first class citizen. The query above would look like this:

var query = _dbContext
  .Table1
  .LeftJoin(_dbContext.Table2, t1 => t1.T2Id, t2 => t2.Id, (t1, t2) => new { t1, t2 });

As of the time of writing (4th December 2024), it is unclear whether or not the query syntax will have a new keyword representing the LeftJoin operator. But it is likely that it will be added to the method syntax. If not - head over to the linked article and give it a thumbs up.

LINQ Joins on multiple columns in Entity Framework

I came across a very annoying "issue" with LINQ joins (left joins) in Entity Framework where the compiler drove me nuts!

Infographics Compendium III - Exceptions, EF Sanitized, Operators, ...

This edition has the following infographics:

  • DebuggerDisplayAttribute
  • Entity Framework input and LINQ - is it safe?
  • ExceptionDispatchInfo
  • implicit and explicit operator

Leverage 'is not' Operator for Exception Filtering!

Did you know you can use the 'is not' operator with exception filtering to simplify and improve your error handling in C#?

In this short blog post, I will show you how to use it.

An error has occurred. This application may no longer respond until reloaded. Reload x