简体   繁体   中英

join not returning all elements in left table C# lambda

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

在此输入图像描述

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:

在此输入图像描述

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

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

what would be missing from my join?

Presumably there are no entries in fact which have the corresponding Cod_articulo values (eg 60155 for posicion 3). Join in LINQ represents an inner join, where there has to be an entry in both sources in order to create an appropriate result.

If you want a left join, you'd typically use GroupJoin , so that each element on the "left" side ends up matching a group of entries from the "right" side, where that group may be empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM