C# Tips and Tricks #4 – Using Zip method in C# to add Integers at each positon of two arrays

Zip method in C# in an interesting extension method that lets the developers to join together two array sequences (IEnumerable). It just processes each element in the 2 IEnumerable collections together.

Assume that you have two arrays of 3 elements each and you wish to show the sum of each index values of the source arrays , you can use the zip extension method in C# as shows below.

using System;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var arr1 = new int[] { 5 , 6 , 3 };
            var arr2 = new int[] { 5 , 8 , 2};

            var combinedArray = arr1.Zip(arr2, (val1, val2) => (val1 + val2));

            foreach (var indexVal in combinedArray)
            {
                Console.WriteLine(indexVal);
            }
            Console.ReadLine();
        }
    }
}

Output

10
14
5

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...