Export (0) Print
Expand All

Enumerable.Zip<TFirst, TSecond, TResult> Method

Merges two sequences by using the specified predicate function.

Namespace:  System.Linq
Assembly:  System.Core (in System.Core.dll)

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
	this IEnumerable<TFirst> first,
	IEnumerable<TSecond> second,
	Func<TFirst, TSecond, TResult> resultSelector
)

Type Parameters

TFirst

The type of the elements of the first input sequence.

TSecond

The type of the elements of the second input sequence.

TResult

The type of the elements of the result sequence.

Parameters

first
Type: System.Collections.Generic.IEnumerable<TFirst>
The first sequence to merge.
second
Type: System.Collections.Generic.IEnumerable<TSecond>
The second sequence to merge.
resultSelector
Type: System.Func<TFirst, TSecond, TResult>
A function that specifies how to merge the elements from the two sequences.

Return Value

Type: System.Collections.Generic.IEnumerable<TResult>
An IEnumerable<T> that contains merged elements of two input sequences.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type IEnumerable<TFirst>. When you use instance method syntax to call this method, omit the first parameter.

ExceptionCondition
ArgumentNullException

first or second is null.

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.

The following code example demonstrates how to use the Zip<TFirst, TSecond, TResult> 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)
         outputBlock.Text += item + "\n";

      // This code produces the following output:

      // 1 one
      // 2 two
      // 3 three



Silverlight

Supported in: 5, 4

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Community Additions

Show:
© 2014 Microsoft