C# LINQ Zip — Complete Guide
In this tutorial, you'll learn about C# LINQ Zip. We cover key concepts, practical examples, and best practices.
You have two parallel lists — names and scores — where the first name corresponds to the first score. You loop with an index to pair them. The LINQ Zip method combines two sequences element by element into a single sequence.
Wrong
var names = new[] { "Alice", "Bob", "Charlie" };
var scores = new[] { 85, 92, 78 };
var paired = new List<(string, int)>();
for (int i = 0; i < names.Length && i < scores.Length; i++)
{
paired.Add((names[i], scores[i]));
}
Output: [("Alice", 85), ("Bob", 92), ("Charlie", 78)] — works, but requires manual index management and bounds checking.
Right
var names = new[] { "Alice", "Bob", "Charlie" };
var scores = new[] { 85, 92, 78 };
var paired = names.Zip(scores).ToList();
// [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
Output: Same tuples. Zip pairs elements from the two sequences at the same position.
With a result selector (C# 9+):
var result = names.Zip(scores, (name, score) => $"{name}: {score}").ToList();
// ["Alice: 85", "Bob: 92", "Charlie: 78"]
Zip stops when the shorter sequence ends:
var a = new[] { 1, 2, 3 };
var b = new[] { 10, 20 };
var zipped = a.Zip(b).ToList(); // [(1, 10), (2, 20)] — 3rd element dropped
Prevention
- Use
Zipto combine parallel sequences instead of indexed loops. - Use
Zipwith a result selector for immediate transformation. - Use
Zipwith three sequences in .NET 6+:a.Zip(b, c). - Use
ZipwithSelectfor complex combinations. - Be aware that
Ziptruncates to the shorter sequence — ensure equal lengths or handle accordingly. - Use
Enumerable.RangewithZipto add sequential numbers to a sequence.
Common Mistakes with linq zip
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Zip is used in Doda Browser to combine UI labels with their localized translations. For more LINQ, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro