Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join not returning all elements in left table C# lambda

Tags:

c#

join

linq

I have 2 tables, the left table has data like this:

enter image description here

I do a left join with another table with the following expression:

 var result = posicion.Join(fact,
                            p => p.Cod_articulo,
                            f => f.Cod_articulo,
                            (p, f) => new { p.Posicion, p.Cant_historico, 
                                            p.Cod_articulo, f.Cantidad_facturada });

The problem is that the results don't include some items from the left table as seen below:

enter image description here

As you can see in the result there is no data for position 3, 6 etc. what would be missing from my join?

like image 390
mmilan Avatar asked Mar 21 '23 20:03

mmilan


1 Answers

You need to do group join (that is left join in Linq). It's better to do with query syntax:

from p in posicion
join f in fact
    on p.Cod_articulo equals f.Cod_articulo into g // GroupJoin
from pf in g.DefaultIfEmpty()
select new { 
   p.Posicion, 
   p.Cant_historico, 
   p.Cod_articulo, 
   Cantidad_facturada = (pf == null) ? null : pf.Cantidad_facturada 
}

This query selects all facts corresponding to posicion p into group g. Then from each group we select results, even if there is no corresponding facts for current posicion (that is DefaultIfEmpty case).

Lambda syntax will be much less readable:

posicion.GroupJoin(fact,
                   p => p.Cod_articulo,
                   f => f.Cod_articulo,
                  (p, g) => new { p, g })
        .SelectMany(x => x.g.DefaultIfEmpty(), (x, pf) => new {
                x.p.Posicion, 
                x.p.Cant_historico, 
                x.p.Cod_articulo, 
                Cantidad_facturada = (pf == null) ? null : pf.Cantidad_facturada 
        });

Consider also reading this MSDN article: How to: Perform Left Outer Joins

like image 153
Sergey Berezovskiy Avatar answered Mar 31 '23 19:03

Sergey Berezovskiy