tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Interleaving two IEnumerable sources using only LINQ methods

27 Jul 2015 1 mins .NET, C#, LINQ

I was cleaning up some old posts and converting them to Markdown on this blog and I came across this post. Although it’s still valid and works fine I’ve got an idea. Is it possible to write it using only LINQ methods? Thus not being imperative? You might be wondering: “Why?". But I just like these small brain teasers. 😃

OK, back to business. Of course it’s possible and it’s not even crazy ugly construct.

internal static IEnumerable<T> Interleave<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
	return first.Zip(second, (a, b) => new[] { a, b }).SelectMany(x => x);
}

Of course there’s a small difference how this method handles IEnumerables with different length compared to the other. But frankly I don’t know what’s the “correct” behavior (should it be allowed, for example?). Both – the old one and the new one – seem to be fine. Heck there’s even a third option. I’ll leave that for others. There’s not enough small brain teasers. 😃

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.