Monday, 12 October 2020

C# - LINQ - Zip() Method

 Enumerable.Zip Method

Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.

The following code example demonstrates how to use the Zip method to merge two sequences.

int[] numbers = { 1, 2, 3, 4 };

string[] words = { "one", "two", "three" };

var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);

foreach (var item in numbersAndWords)

    Console.WriteLine(item);

 // This code produces the following output:

// 1 one

// 2 two

// 3 three

Remarks

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.

The method merges each element of the first sequence with an element that has the same index in the second sequence. If the sequences do not have the same number of elements, the method merges sequences until it reaches the end of one of them. For example, if one sequence has three elements and the other one has four, the result sequence will have only three elements.

No comments:

Post a Comment