Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve Left Excluding JOIN using LINQ?

Tags:

How to achieve Left Excluding JOIN using LINQ?

In SQL:

SELECT <select_list>  FROM Table_A A LEFT JOIN Table_B B ON A.Key = B.Key WHERE B.Key IS NULL 
like image 886
French Boy Avatar asked Jul 12 '11 10:07

French Boy


People also ask

Can we use left join in LINQ?

You can use LINQ to perform a left outer join by calling the DefaultIfEmpty method on the results of a group join.

Is GroupJoin left join?

This is actually not nearly as crazy as it seems. Basically GroupJoin does the left outer join, the SelectMany part is only needed depending on what you want to select.

Is LINQ join inner or outer?

One commonly used feature of Language-Integrated Query (LINQ) is the facility to combine two sequences of related data using joins. The standard join operation provides an inner join but with a minor modification can be changed to give a left outer join.

What is DefaultIfEmpty in LINQ?

The DefaultIfEmpty operator is used to replace an empty collection or sequence with a default valued singleton collection or sequence. Or in other words, it returns a collection or sequence with default values if the source is empty, otherwise return the source.


2 Answers

You need DefaultIfEmpty() for the LEFT JOIN, then you can check if the joined value is null:

var result = from a in Table_A              join b in Table_B on a.Key equals b.Key into j              from b in j.DefaultIfEmpty()              where b == null              select new { ... }; 
like image 147
dahlbyk Avatar answered Sep 22 '22 01:09

dahlbyk


Easier would be to write like this:

var result = from a in Table_A              where !Table_B.Any(b => b.Key == a.key)              select new { ... }; 
like image 23
Magnus Avatar answered Sep 22 '22 01:09

Magnus