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

前端 未结 7 1171
灰色年华
灰色年华 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:56

    Whilst the accepted answer works and is good for Linq to Objects it bugged me that the SQL query isn't just a straight Left Outer Join.

    The following code relies on the LinkKit Project that allows you to pass expressions and invoke them to your query.

    static IQueryable LeftOuterJoin(
         this IQueryable source, 
         IQueryable inner, 
         Expression> sourceKey, 
         Expression> innerKey, 
         Expression> result
        ) {
        return from a in source.AsExpandable()
                join b in inner on sourceKey.Invoke(a) equals innerKey.Invoke(b) into c
                from d in c.DefaultIfEmpty()
                select result.Invoke(a,d);
    }
    

    It can be used as follows

    Table1.LeftOuterJoin(Table2, x => x.Key1, x => x.Key2, (x,y) => new { x,y});
    

提交回复
热议问题