What is the use of Enumerable.Zip extension method in Linq?

Zip is for combining two sequences into one. For example, if you have the sequences

1, 2, 3

and

10, 20, 30

and you want the sequence that is the result of multiplying elements in the same position in each sequence to obtain

10, 40, 90

you could say

var left = new[] { 1, 2, 3 };
var right = new[] { 10, 20, 30 };
var products = left.Zip(right, (m, n) => m * n);

It is called "zip" because you think of one sequence as the left-side of a zipper, and the other sequence as the right-side of the zipper, and the zip operator will pull the two sides together pairing off the teeth (the elements of the sequence) appropriately.


The Zip operator merges the corresponding elements of two sequences using a specified selector function.

var letters= new string[] { "A", "B", "C", "D", "E" };
var numbers= new int[] { 1, 2, 3 };
var q = letters.Zip(numbers, (l, n) => l + n.ToString());
foreach (var s in q)
    Console.WriteLine(s);

Ouput

A1
B2
C3

Tags:

C#

Linq