tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Interleaving two IEnumerable sources using only LINQ methods

27 Jul 2015 .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. 😃