How to implement left join in JOIN Extension method

后端 未结 3 1745
时光说笑
时光说笑 2020-11-30 01:41

I am trying to implement an outer join on this kind of query for the p.Person table. How would I do this?

This example is taken from http://ashishware.c

3条回答
  •  春和景丽
    2020-11-30 02:04

    Normally left joins in LINQ are modelled with group joins, sometimes in conjunction with DefaultIfEmpty and SelectMany:

    var leftJoin = p.Person.Where(n => n.FirstName.Contains("a"))
                           .GroupJoin(p.PersonInfo, 
                                      n => n.PersonId,
                                      m => m.PersonId,
                                      (n, ms) => new { n, ms = ms.DefaultIfEmpty() })
                           .SelectMany(z => z.ms.Select(m => new { n = z.n, m }));
    

    That will give a sequence of pairs (n, m) where n is the entry from p.Person and m is the entry from p.PersonInfo, but m will be null if there are no matches.

    (It's completely untested, btw - but should give you the idea anyway :)

提交回复
热议问题