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

Pin It

Leave a Reply

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