How to Use LINQ Zip in C#: Simple Guide with Examples
Use
Enumerable.Zip in C# to combine two sequences by pairing elements with the same index into a new sequence. It takes two collections and a function to specify how to merge each pair into a result element.Syntax
The Zip method combines two sequences by matching elements at the same position. It requires two input sequences and a function that defines how to merge each pair of elements.
first: The first sequence.second: The second sequence.resultSelector: A function that takes one element from each sequence and returns a combined result.
csharp
var zippedSequence = first.Zip(second, (firstElement, secondElement) => result);Example
This example shows how to use Zip to combine two lists of numbers by adding their elements pairwise.
csharp
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main() { var numbers1 = new List<int> { 1, 2, 3 }; var numbers2 = new List<int> { 4, 5, 6 }; var sumPairs = numbers1.Zip(numbers2, (a, b) => a + b); foreach (var sum in sumPairs) { Console.WriteLine(sum); } } }
Output
5
7
9
Common Pitfalls
One common mistake is assuming Zip works with sequences of different lengths. It only processes pairs up to the length of the shorter sequence, ignoring extra elements in the longer one.
Another pitfall is forgetting to provide the resultSelector function, which is required to specify how to combine elements.
csharp
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main() { var list1 = new List<int> { 1, 2, 3, 4 }; var list2 = new List<int> { 10, 20 }; // Only pairs up to length 2 are processed var zipped = list1.Zip(list2, (x, y) => x * y); foreach (var item in zipped) { Console.WriteLine(item); } } }
Output
10
40
Quick Reference
- Zip pairs elements by index from two sequences.
- Stops when the shorter sequence ends.
- Requires a function to combine pairs.
- Returns a new sequence of combined results.
Key Takeaways
Use
Zip to combine two sequences element-wise with a custom function.Zip stops at the shortest sequence length, ignoring extra elements.Always provide a
resultSelector function to define how to merge pairs.The result is a new sequence with combined elements from both inputs.
Useful for parallel processing of two related collections.