Left Join Linq example
So the Left Join is the same concept as a SQL Left Join. The left join will join all items from the left side and any on the right side where there is no match, it will be a null.
A basic example
In this example, we are going to perform a left join with two lists.
Method syntax
The syntax is very similar to the GroupJoin. The magical extra bit you will need is the DefaultIfEmpty(). This is the part which figures out if there is no match, use the default, which will be generally null.
Live example: https://dotnetfiddle.net/ga7Tkb
var people = new[]
{
new { Name = "Vernon", Gender = "Male", CountryCode = "GB" },
new { Name = "Carrie", Gender = "Female", CountryCode = "CA" },
new { Name = "Joanna", Gender = "Female", CountryCode = "US" },
new { Name = "Thomas", Gender = "Male", CountryCode = "ES" },
new { Name = "James", Gender = "Male", CountryCode = "GB" },
new { Name = "Elly", Gender = "Female", CountryCode = "US" }
};
var countries = new[]
{
new {CountryName = "United Kingdom", Code = "GB"},
new {CountryName = "United States", Code = "US"},
new {CountryName = "Canada", Code = "CA"},
new {CountryName = "France", Code = "FR"},
new {CountryName = "Spain", Code = "ES"}
};
var q = countries.GroupJoin(people,
arg => arg.Code,
arg => arg.CountryCode,
(c, p) => new {Country = c, People = p})
.SelectMany(arg => arg.People.DefaultIfEmpty(),
(c, p) => new {Country = c, People = p});
// output
//United Kingdom - Vernon
//United Kingdom - James
//United States - Joanna
//United States - Elly
//Canada - Carrie
//France - NULL
//Spain - Thomas
Query syntax
Here, to perform a left join, we carry out the join, then we use the groupby query syntax, into g. Then we specify from pg in g.DefaultIfEmpty(). This is the crucial part where if there are no matches, just use null.
Live example: https://dotnetfiddle.net/wFqYTJ
var people = new[]
{
new { Name = "Vernon", Gender = "Male", CountryCode = "GB" },
new { Name = "Carrie", Gender = "Female", CountryCode = "CA" },
new { Name = "Joanna", Gender = "Female", CountryCode = "US" },
new { Name = "Thomas", Gender = "Male", CountryCode = "ES" },
new { Name = "James", Gender = "Male", CountryCode = "GB" },
new { Name = "Elly", Gender = "Female", CountryCode = "US" }
};
var countries = new[]
{
new {CountryName = "United Kingdom", Code = "GB"},
new {CountryName = "United States", Code = "US"},
new {CountryName = "Canada", Code = "CA"},
new {CountryName = "France", Code = "FR"},
new {CountryName = "Spain", Code = "ES"}
};
var q = from c in countries
join p in people
on c.Code equals p.CountryCode
into g
from pg in g.DefaultIfEmpty()
select new {Country = c, People = pg};
// output
//United Kingdom - Vernon
//United Kingdom - James
//United States - Joanna
//United States - Elly
//Canada - Carrie
//France - NULL
//Spain - Thomas
