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
You can use LINQ to perform a left outer join by calling the DefaultIfEmpty method on the results of a group 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.
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.
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.
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 { ... };
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 { ... };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With