- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements