5
Oct
LINQ and left outer join helper
Previous two functions (function 1, function 2) I presented were doing something that wasn’t core part of LINQ and it was up to you to create it. On the other hand, this function is different. It’s just a helper to simplify writing of left outer join (or right outer join, depending on what collection you consider to be on left/right side). Not because it’s hard to write it, but because it involves couple of lines and repeating it all the time is just boring.
internal static IEnumerable<TResult> LeftOuterJoin<TOuter, TLeft, TKey, TResult>(this IEnumerable<TOuter> outer, IEnumerable<TLeft> left, Func<TOuter, TKey> outerKeySelector, Func<TLeft, TKey> leftKeySelector, Func<TOuter, TLeft, TResult> resultSelector)
{
return
from o in outer
join r in left on outerKeySelector(o) equals leftKeySelector(r) into j
from r in j.DefaultIfEmpty()
select resultSelector(o, r);
}
Nothing tricky. You can find this in many examples, I just wrapped it into method and parametrized it a little. Enjoy.



There's 3 Comments So Far
October 5th, 2010 at 21:24
Interesting, but the annoying thing about this helper is that you can use it only with the extension methods/lambda function syntax (and the method takes quite a number of parameters…). I think it should be possible to write some wrappers that would allow you to write something like:
from o in outer
join r in left.WithLeftOuterJoin() on … equals …
select …;
(Using similar trick as here: http://tomasp.net/blog/custom-linq-grouping.aspx)
October 5th, 2010 at 22:50
Yes, you’re right. That should be doable. But as I’m not using code comprehension almost at all, I’ll left it for reader.
Who Linked To This Post?
Share your thoughts, leave a comment!