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.
If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.
SHARE: