TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Zip Method

This C# tutorial shows how to use the Zip method from System.Linq.

Zip. The Zip extension method acts upon two collections. It processes each element in two series together. With a Func instance, we use Zip to handle elements from two C# collections in parallel.

Extension MethodFunc

Example. In this program, we declare two arrays of five integer elements each. Then, we invoke the Zip method. The first argument to the Zip method is the secondary array we want to process in parallel.

Int Array

And: The second argument to the Zip method is a lambda expression that describes a Func instance.

Arguments: Two integer parameters are the arguments to the Func, and the return value is the two parameters added together.

IntReturn

C# program that uses Zip extension method

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Two source arrays.
	var array1 = new int[] { 1, 2, 3, 4, 5 };
	var array2 = new int[] { 6, 7, 8, 9, 10 };

	// Add elements at each position together.
	var zip = array1.Zip(array2, (a, b) => (a + b));

	// Look at results.
	foreach (var value in zip)
	{
	    Console.WriteLine(value);
	}
    }
}

Output

7
9
11
13
15

In this example, the Func expression is processed over all five elements of both arrays. The result value is each of the two arrays with their parallel elements added together—a zipped-up array.

Uneven source data? If you happen to have two collections with an unequal number of elements, the Zip method will only continue to the shortest index where both elements exist. No errors will occur if the two collections are uneven.

Tip: Zip will not throw an exception if the two collections are of unequal length.

Summary. The Zip extension method provides a way for you to process two collections or series in parallel. This can replace a lot of for-loops where the index variable is necessary to process two arrays at once.

For


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf