C# Zip Method (Use Lambda on Two Collections)

Use the Zip method from System.Linq. Zip uses a lambda on the elements from two collections.

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.ExtensionFuncLINQ

Example. In this program, we declare 2 arrays of 5 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 2 parameters added together.

Int, uintReturn
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

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 2 arrays at once.For
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to