How to iterate two Lists or Arrays with one foreach statement in C#?

CsharpProgrammingServer Side Programming

Set two arrays.

var val = new [] { 20, 40, 60};
var str = new [] { "ele1", "ele2", "ele3"};

Use the zip() method to process the two arrays in parallel.

var res = val.Zip(str, (n, w) => new { Number = n, Word = w });

The above fetches both the arrays with int and string elements respectively.

Now, use foreach to iterate the two arrays −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;

public class Demo {
   public static void Main() {
      var val = new [] { 20, 40, 60};
      var str = new [] { "ele1", "ele2", "ele3"};
      var res = val.Zip(str, (n, w) => new { Number = n, Word = w });

      foreach(var a in res) {
         Console.WriteLine(a.Number + a.Word);
      }
   }
}

Output

20ele1
40ele2
60ele3
raja
Published on 11-Sep-2018 11:29:01
Advertisements