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


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements