LINQ: Writing an Interweave extension

As we have seen in our last few posts on LINQ, the framework comes with some great extension methods to handle the merging of multiple collections into a single one.

However, there are things that LINQ can not easily do on its own. One of them is interweaving collections, i.e. merging them by taking elements from each input collection alternatively.

For example, given the inputs 1, 2, 3 and a, b, c we would get the output 1, a, 2, b, 3, c.

Today, we will look into how to best implement this ourselves.

Continue reading →

LINQ: Flatten nested collections with SelectMany

Last time we looked at some of the possible ways of using LINQ to merge two collections into one.

Today we are going to look at another method that can be used to combine collections: SelectMany.

As an example of how multiple LINQ methods can be combined for interesting results we will use SelectMany and Zip to quickly implement a merging operation that LINQ does not have a method for: Interweaving elements from multiple collections.

Spoiler: Our interweaving implementation with SelectMany will be nice and short, but it will be sub-optimal with regards to performance. We will tackle that problem in a follow up post.

Continue reading →

LINQ: merging collections with Concat, Zip, and Join

Continuing my series of posts on LINQ, today I want to write about a few of the LINQ extension methods that take multiple input collections and return a single one.

Specifically, I want to take a look at the following methods: Concat(), Zip() and Join(). These all take two input collections, and combine their elements into a single resulting collection in different ways.

Continue reading →