Home
Search
C# Zip MethodUse the Zip method from System.Linq. Zip uses a lambda on the elements from two collections.
dot net perls
Zip. The Zip extension method acts upon 2 collections. It processes each element in 2 series together. Zip() is found in System.Linq, so we must include this namespace.
Func info. With a Func instance, we use Zip to handle elements from two C# collections in parallel. Any IEnumerable can be zipped.
Extension
Func
Example. We declare 2 string arrays. Then, we invoke the Zip method. The first argument to the Zip method is the secondary array we want to process in parallel.
Array
And The second argument to the Zip method is a lambda expression that describes a Func instance.
Arguments Two strings are the arguments to the Func, and the return value is the 2 strings concatenated.
Return
C# program that uses Zip extension method
using System; using System.Linq; class Program { static void Main() { // Two source arrays. var array1 = new string[] { "blue", "red", "green" }; var array2 = new string[] { "sky", "sunset", "lawn" }; // Concatenate elements at each position together. var zip = array1.Zip(array2, (a, b) => (a + "=" + b)); // Look at results. foreach (var value in zip) { Console.WriteLine("ZIP: {0}", value); } } }
ZIP: blue=sky ZIP: red=sunset ZIP: green=lawn
Unequal counts. If you happen to have 2 collections with an unequal number of elements, the Zip method will only continue to the shortest index where both elements exist.
Info No errors will occur if the two collections are uneven. Zip will not throw an exception if the two collections are of unequal length.
C# program that shows zip, unequal counts
using System; using System.Linq; class Program { static void Main() { var test1 = new int[] { 1, 2 }; var test2 = new int[] { 3 }; // Zip unequal collections. var zip = test1.Zip(test2, (a, b) => (a + b)); foreach (var value in zip) { Console.WriteLine(value); } } }
4
A summary. Zip() processes 2 collections or series in parallel. This can replace a lot of for-loops where the index variable is necessary to process 2 arrays at once.
For
Home
© 2007-2021 sam allen. see site info on the changelog