Merging IEnumerable Sequences in C# with LINQ

The Zip method allows us to join IEnumerable sequences together by interleaving the elements in the sequences.

Zip is an extension method on IEnumerable. For example to zip together a collection of names with ages we could write:

var names = new [] {"John", "Sarah", "Amrit"};

var ages = new[] {22, 58, 36};

var namesAndAges = names.Zip(ages, (name, age) => name + " " + age);    

This would produce an IEnumerable<string> containing three elements:

  • “John 22”
  • “Sarah 58”
  • “Amrit 36”

If one sequence is shorter that the other, the “zipping” will stop when the end of the shorter sequence is reached. So if we added an extra name:

var names = new [] {"John", "Sarah", "Amrit", "Bob"};

We’d end up with the same result as before, “Bob” wouldn’t be used as there isn’t a corresponding age for him.

We can also create objects in our lambda, this example shows how to create an IEnumerable of two-element Tuples:

var names = new [] {"John", "Sarah", "Amrit"};

var ages = new[] {22, 58, 36};

var namesAndAges = names.Zip(ages, (name, age) => Tuple.Create(name, age)); 

This will produce an IEnumerable<Tuple<String,Int32>> that contains three Tuples, with each Tuple holding a name and age.

 

(The .Zip method is one of a smorgasbord of C# Tips and Traps that I cover in my Pluralisight C# courses.)

Add comment

Loading