System.Linq.Enumerable.Zip
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
this IEnumerable<TFirst> first,
this IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector
)
Description
Applies a transform function to the corresponding elements of two sequences and returns an sequence of the results.
Parameters
- first: The first sequence to combine.
- second: The second sequence to combine.
- resultSelector: A transform function to apply to each source element pair.
Returns
An IEnumerable<TResult>
that contains the elements produced by applying the transform function to each pair of corresponding elements in the input sequences.
Remarks
The sequences can have different lengths. The resulting sequence will be as long as the shorter of the two input sequences. If either sequence is null
, an ArgumentNullException
is thrown.
Example
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4 };
List<string> letters = new List<string> { "a", "b", "c", "d", "e" };
// Combine numbers and letters into pairs
var combined = numbers.Zip(letters, (num, letter) => new { Number = num, Letter = letter });
foreach (var item in combined)
{
Console.WriteLine($"Number: {item.Number}, Letter: {item.Letter}");
}
// Output:
// Number: 1, Letter: a
// Number: 2, Letter: b
// Number: 3, Letter: c
// Number: 4, Letter: d
}
}