Mastering the Zip Function in C#: Practical Use Cases and Examples

Madhawa Polkotuwa
4 min readAug 21, 2024

--

The Zip function in C# is a handy tool that lets you combine two sequences into a single sequence by pairing elements from both collections based on their position. Whether you're working with simple lists or handling complex data sets, Zip makes your code more concise and readable.

In this post, we’ll explore what the Zip function is, how it works, and look at some real-world use cases where it can be applied effectively.

What Is the Zip Function?

The Zip function merges two collections by pairing elements together at corresponding positions. It’s like zipping up a jacket—two sides come together element by element.

Here’s a basic syntax:

var result = collection1.Zip(collection2, (item1, item2) => new {
Property1 = item1,
Property2 = item2
});

The lambda function allows you to specify how the paired elements should be combined.

Example 1: Pairing Color Names with Hex Codes

Let’s start with a simple example. Suppose you have two arrays: one containing color names and the other containing their respective hex codes.

var colorNames = new[] { "Navi Blue", "Light Orange", "Light Green" };
var hexCode = new[] { "#000080", "#FFD580", "#90EE90" };

var colors = colorNames.Zip(hexCode, (name, hex) => new {
ColorName = name,
HexCode = hex
});
colors
{ ColorName = Navi Blue, HexCode = #000080 }
{ ColorName = Light Orange, HexCode = #FFD580 }
{ ColorName = Light Green, HexCode = #90EE90 }

This code produces a collection that pairs each color name with its hex code.

Example 2: Merging Employee Names and Salaries

Imagine you have two arrays: one with employee names and the other with their salaries. You want to combine these arrays to create a list of objects representing employees and their salaries.

var employeeNames = new[] { "Alice", "Bob", "Charlie", "Diana" };
var employeeSalaries = new[] { 60000, 55000, 70000, 50000 };

var employees = employeeNames.Zip(employeeSalaries, (name, salary) => new {
Name = name,
Salary = salary
});
employees
{ Name = Alice, Salary = 60000 }
{ Name = Bob, Salary = 55000 }
{ Name = Charlie, Salary = 70000 }
{ Name = Diana, Salary = 50000 }

Example 3: Combining Product Details with Discounts

Now let’s look at something more complex. Suppose you have product names, their prices, and the discount percentages. You can use Zip to merge this information and calculate the final price after applying discounts.

var productNames = new[] { "Laptop", "Smartphone", "Tablet" };
var productPrices = new[] { 1500.00m, 800.00m, 300.00m };
var discounts = new[] { 0.10m, 0.15m, 0.05m }; // Discount percentages: 10%, 15%, 5%

var productsWithDiscounts = productNames
.Zip(productPrices, (name, price) => new { Name = name, Price = price })
.Zip(discounts, (product, discount) => new {
product.Name,
product.Price,
Discount = discount,
FinalPrice = product.Price - (product.Price * discount)
});
productsWithDiscounts
{ Name = Laptop, Price = 1500.00, Discount = 0.10, FinalPrice = 1350.0000 }
{ Name = Smartphone, Price = 800.00, Discount = 0.15, FinalPrice = 680.0000 }
{ Name = Tablet, Price = 300.00, Discount = 0.05, FinalPrice = 285.0000 }

With just a few lines of code, you can manage and transform product data efficiently.

Example 4: Merging Student Grades Across Different Subjects

Here’s another useful scenario: combining student names with their grades in multiple subjects to calculate an overall average.

var students = new[] { "John", "Emily", "David" };
var mathGrades = new[] { 85, 92, 78 };
var scienceGrades = new[] { 88, 90, 83 };

var studentGrades = students
.Zip(mathGrades, (student, math) => new { Student = student, MathGrade = math })
.Zip(scienceGrades, (student, science) => new {
student.Student,
student.MathGrade,
ScienceGrade = science,
AverageGrade = (student.MathGrade + science) / 2.0
});
studentGrades
{ Student = John, MathGrade = 85, ScienceGrade = 88, AverageGrade = 86.5 }
{ Student = Emily, MathGrade = 92, ScienceGrade = 90, AverageGrade = 91 }
{ Student = David, MathGrade = 78, ScienceGrade = 83, AverageGrade = 80.5 }

This example shows how the Zip function can be used to summarize performance data across different categories.

Why Use the Zip Function?

The Zip function is a great choice when:

  • You have related data split across two collections.
  • You want a cleaner and more readable approach to merging datasets.
  • You need to perform operations while combining the data, like calculating totals or averages.

Conclusion

The Zip function is more than just a convenient feature—it’s a powerful tool for handling multiple related datasets. Whether you’re dealing with simple pairs or complex multi-step combinations, Zip helps you streamline your code.

Try using the Zip function in your next project and see how it simplifies your data handling!

--

--

No responses yet