Friday, April 8, 2011

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

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 = f, Bar = result }

How would I express the same task using extension methods? E.g.

Foo.GroupJoin(Bar, f => f.Foo_Id, b => b.Foo_Id, (f,b) => ???)
    .Select(???)
From stackoverflow
  • You can use Reflector to decompile the generated code and see which extension methods are used.

    Brehtt : +1 for teaching a man to fish...
    Nik : FYI Resharper will also let you switch back and forth between them real easy
  • var qry = Foo.GroupJoin(
              Bar, 
              foo => foo.Foo_Id,
              bar => bar.Foo_Id,
              (x,y) => new { Foo = x, Bars = y })
        .SelectMany(
              x => x.Bars.DefaultIfEmpty(),
              (x,y) => new { Foo=x.Foo, Bar=y});
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.