Collections & LINQ · Lesson 27

Zip and the contract for paired sequences

Combine values by position while checking whether unmatched tails are acceptable.

How it works

Zip combines corresponding elements from two sequences. It pairs the first element of one sequence with the first element of the other, then the second with the second, and so on. This is useful when the data contract is positional, such as pairing prepared column labels with their values or comparing observations from two aligned snapshots.

Zip stops when either sequence ends. It does not throw merely because one input is longer, and it does not invent a value for the unmatched tail. That rule is convenient for some calculations and dangerous for others. When every identifier must have a measurement, validate equal lengths or use a representation that stores each pair together before relying on positional alignment.

Walk through the example. Three product labels are paired with only two quantities. The result contains two rows: A with four and B with seven. Product C has no partner and contributes no row. The example then prints the unequal-length check explicitly. Keeping that check visible demonstrates that a successful Zip call is not evidence that every input record has been represented.

Watch the boundary. Parallel arrays are easy to misalign when one is sorted, filtered, or updated independently. Equal lengths alone cannot prove that the positions still refer to the same entities. If labels and quantities belong together throughout the workflow, use a record or tuple per item. Choose Zip when positional pairing is the actual contract, rather than using it to repair a weak data model.

Practice independently. Write a comparison of predicted and actual temperatures from two equal-length arrays. Print the difference at every position. Add a shorter actual sequence and choose whether the program should reject the mismatch or report missing observations. Then replace the parallel arrays with one array of records and explain which kinds of alignment mistakes the new representation prevents.

A working example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;

string[] codes = { "A", "B", "C" };
int[] quantities = { 4, 7 };
var paired = codes.Zip(quantities, (code, quantity) => $"{code}:{quantity}").ToArray();
Console.WriteLine(paired.Length);
foreach (string row in paired) Console.WriteLine(row);
Console.WriteLine(codes.Length == quantities.Length);

Expected output

2
A:4
B:7
False
Try this
Zip ends with the shorter input; validate alignment when unmatched data would be an error.