Zip
Learn to combine two collections in parallel with Zip.
Parallel combine with Zip
Zip combines two sequences index by index; each step takes one item from each sequence and produces a result. The result length matches the shorter sequence.
Example: names.Zip(ages, (n, a) => n + " " + a) pairs a name with an age at each index. If one sequence is shorter, Zip stops at that length; the extra items are dropped.
The result selector
The result selector of Zip takes two parameters: the item from the first sequence and the item from the second. Its return value is the result for each pair. You can choose any result type.
On .NET 6 and later Zip can be called without a result selector; it then yields each pair as a tuple: names.Zip(ages) → IEnumerable<(string, int)>.
Exercise Zip names with ages
Combine the names and ages lists below with Zip. Print each pair as name age with Console.WriteLine.
Show example solution
Merge with var pairs = names.Zip(ages, (n, a) => n + " " + a); then write foreach (var p in pairs) Console.WriteLine(p);.
Example solution:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var names = new List<string> { "Ayşe", "Ali" };
var ages = new List<int> { 30, 25 };
var pairs = names.Zip(ages, (n, a) => n + " " + a);
foreach (var p in pairs)
{
Console.WriteLine(p);
}
}
}
Test yourself
-
Match the method to its behavior
- Zip
- Index-based pair
- Join
- Key-based merge
- Aggregate
- Fold to one value
- GroupBy
- Group by key
-
Zip on different-length sequences?
- Stops at the shorter one
- Throws an exception
- Continues to the longer one
- Takes only the first item
Show answer
Stops at the shorter one — Correct. Zip stops when the shorter sequence ends; extras are dropped.
-
Complete the Zip call
var pairs = names.____(ages, (n, a) => n + " " + a);Show answer
var pairs = names.Zip(ages, (n, a) => n + " " + a);