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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...