What is the purpose of ZIP extension method? Explain with example.

 Posted by Niladri.Biswas on 7/11/2012 | Category: C# Interview questions | Views: 1418 | Points: 40
Answer:

The new ZIP extension method introduced in C#4.0 merges two collection sequences by using a predicate function.It is a Combining operator.It combines items from one collection with items from second that are in the same position in the collection.

If Collection A has N items and Collection B has N items (N = 1, 2, 3, 4...), the ZIP extension method will perform the operation as A[N] with B[N].


Let us see an example

Sample input

List<int> firstCollection = new List<int> { 11,12,13,14,15 };
List<int> secondCollection = new List<int> { 6,7,8,9,10 };


Aim:

To perform x[i] + y[i]

Solution using ZIP extension method



var firstCollection = new List<int> { 11,12,13,14,15 };
var secondCollection = new List<int> { 6,7,8,9,10 };

firstCollection
.Zip(secondCollection, (a, b) => a + b)
.ToList()
.ForEach(i => Console.WriteLine(i));



Result


17
19
21
23
25


Explanation:

We are merging the two sequences by using the predicate function ((a, b) => a + b) and using the Foreach extension method performing the display action on each element.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response