0
0
C Sharp (C#)programming~5 mins

Zip operation in C Sharp (C#)

Choose your learning style9 modes available
Introduction

The Zip operation combines two lists by pairing their elements one by one. It helps to work with two collections together easily.

You have two lists of related data and want to process them together.
You want to combine names and ages from two separate lists into pairs.
You need to merge two sequences to create a new sequence of combined values.
Syntax
C Sharp (C#)
var zipped = list1.Zip(list2, (first, second) => /* combine first and second */);

The Zip method pairs elements from two sequences until one runs out.

The lambda expression defines how to combine each pair.

Examples
This example pairs numbers with words and prints them like "1: one".
C Sharp (C#)
var numbers = new List<int> {1, 2, 3};
var words = new List<string> {"one", "two", "three"};
var zipped = numbers.Zip(words, (n, w) => n + ": " + w);
foreach (var item in zipped) {
    Console.WriteLine(item);
}
This example multiplies pairs of numbers. It stops when the shorter array ends.
C Sharp (C#)
var a = new[] {10, 20, 30};
var b = new[] {1, 2};
var zipped = a.Zip(b, (x, y) => x * y);
foreach (var product in zipped) {
    Console.WriteLine(product);
}
Sample Program

This program pairs each fruit with its color and prints a sentence describing it.

C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
    static void Main() {
        var fruits = new List<string> {"apple", "banana", "cherry"};
        var colors = new List<string> {"red", "yellow", "dark red"};

        var zipped = fruits.Zip(colors, (fruit, color) => $"{fruit} is {color}");

        foreach (var description in zipped) {
            Console.WriteLine(description);
        }
    }
}
OutputSuccess
Important Notes

If the lists have different lengths, Zip stops at the shortest one.

Zip is useful to avoid manual loops when combining two collections.

Summary

Zip pairs elements from two collections one by one.

It uses a function to combine each pair into a new result.

It stops when the shorter collection ends.