tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

LINQ and left outer join helper

5 Oct 2010 1 mins .NET, C#, LINQ

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.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.