New! GraphQL.NET Cookbook by Senthil Kumar Balu

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

Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.