Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Linq Zip Method
The Zip method in C# LINQ is used to merge two sequences element by element using a specified predicate function. It combines corresponding elements from two collections into a single sequence, creating pairs from the first element of each sequence, then the second element of each, and so on.
The method stops when the shorter sequence is exhausted, making it safe to use with sequences of different lengths.
Syntax
Following is the syntax for the Zip method −
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TSecond, TResult> resultSelector
)
Parameters
-
first − The first sequence to merge.
-
second − The second sequence to merge.
-
resultSelector − A function that specifies how to merge the elements from the two sequences.
Return Value
Returns an IEnumerable<TResult> that contains merged elements from the two input sequences.
Using Zip to Merge Arrays
Example
using System;
using System.Linq;
public class Demo {
public static void Main() {
int[] intArray = { 10, 20, 30, 40 };
string[] stringArray = { "Jack", "Tim", "Henry", "Tom" };
var mergedSeq = intArray.Zip(stringArray, (one, two) => one + " " + two);
foreach (var ele in mergedSeq)
Console.WriteLine(ele);
}
}
The output of the above code is −
10 Jack 20 Tim 30 Henry 40 Tom
Using Zip with Different Length Sequences
Example
using System;
using System.Linq;
public class Demo {
public static void Main() {
int[] numbers = { 1, 2, 3, 4, 5 };
string[] letters = { "A", "B", "C" };
var result = numbers.Zip(letters, (num, letter) => $"{letter}{num}");
Console.WriteLine("Result when first sequence is longer:");
foreach (var item in result)
Console.WriteLine(item);
}
}
The output of the above code is −
Result when first sequence is longer: A1 B2 C3
Using Zip to Create Objects
Example
using System;
using System.Linq;
public class Person {
public string Name { get; set; }
public int Age { get; set; }
public override string ToString() {
return $"Name: {Name}, Age: {Age}";
}
}
public class Demo {
public static void Main() {
string[] names = { "Alice", "Bob", "Charlie" };
int[] ages = { 25, 30, 35 };
var people = names.Zip(ages, (name, age) => new Person { Name = name, Age = age });
foreach (var person in people)
Console.WriteLine(person);
}
}
The output of the above code is −
Name: Alice, Age: 25 Name: Bob, Age: 30 Name: Charlie, Age: 35
Conclusion
The Zip method in LINQ provides an efficient way to merge two sequences element by element using a custom function. It's particularly useful for combining related data from different collections and automatically handles sequences of different lengths by stopping at the shortest sequence.
