Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make LEFT JOIN in Lambda LINQ expressions

How to make this expression as LEFT JOIN

var query = order.Items.Join(productNonCriticalityList,
    i => i.ProductID,
    p => p.ProductID,
    (i, p) => i);
like image 397
Sergey Avatar asked Feb 03 '14 20:02

Sergey


People also ask

Can we use left join in LINQ?

A left outer join is a join in which each element of the first collection is returned, regardless of whether it has any correlated elements in the second collection. 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.

Can we do Joins in LINQ?

In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables. In LINQ, explicit join clauses are only required when two source sequences are not tied by any relationship.


2 Answers

And this is the more complicated way using lambda expressions to write it:

order.Items
   .GroupJoin (
      productNonCriticalityList, 
      i => i.ProductID, 
      p => p.ProductID, 
      (i, g) => 
         new  
         {
            i = i, 
            g = g
         }
   )
   .SelectMany (
      temp => temp.g.DefaultIfEmpty(), 
      (temp, p) => 
         new  
         {
            i = temp.i, 
            p = p
         }
   )
like image 113
Magnus Avatar answered Sep 16 '22 13:09

Magnus


I would recommend switching to from syntax and you can use the into keyword.

It does the same thing as the method syntax and is far more readable (IMO).

(from l1 in myFirstDataSet
join l2 in mySecondDataSet on l1.<join_val> equals l2.<join_val> into leftJ
from lj in leftJ.DefaultIfEmpty()
where <your_where_clause>
select <something>).ToList();
like image 28
Timeout Avatar answered Sep 16 '22 13:09

Timeout