How do you perform a left outer join using linq extension methods

前端 未结 7 1246
灰色年华
灰色年华 2020-11-22 10:12

Assuming I have a left outer join as such:

from f in Foo
join b in Bar on f.Foo_Id equals b.Foo_Id into g
from result in g.DefaultIfEmpty()
select new { Foo          


        
7条回答
  •  野性不改
    2020-11-22 10:48

    Group Join method is unnecessary to achieve joining of two data sets.

    Inner Join:

    var qry = Foos.SelectMany
                (
                    foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id),
                    (foo, bar) => new
                        {
                        Foo = foo,
                        Bar = bar
                        }
                );
    

    For Left Join just add DefaultIfEmpty()

    var qry = Foos.SelectMany
                (
                    foo => Bars.Where (bar => foo.Foo_id == bar.Foo_id).DefaultIfEmpty(),
                    (foo, bar) => new
                        {
                        Foo = foo,
                        Bar = bar
                        }
                );
    

    EF and LINQ to SQL correctly transform to SQL. For LINQ to Objects it is beter to join using GroupJoin as it internally uses Lookup. But if you are querying DB then skipping of GroupJoin is AFAIK as performant.

    Personlay for me this way is more readable compared to GroupJoin().SelectMany()

提交回复
热议问题