Home > Backend Development > C++ > How Can I Iterate Through Multiple Lists Simultaneously Using a Single ForEach Loop in C#?

How Can I Iterate Through Multiple Lists Simultaneously Using a Single ForEach Loop in C#?

Mary-Kate Olsen
Release: 2025-01-03 22:08:41
Original
804 people have browsed it

How Can I Iterate Through Multiple Lists Simultaneously Using a Single ForEach Loop in C#?

Iterating Multiple Lists with a Unified ForEach Loop in C#

In C#, one may encounter scenarios where iterating over multiple lists simultaneously with a single foreach loop is desired. This article explores a solution to this problem using the Zip operation introduced in .NET 4.

The Zip operation enables developers to combine elements from multiple sequences into a single sequence, allowing for paired iteration. Consider the following example:

List<string> listA = new List<string> { "string", "string" };
List<string> listB = new List<string> { "string", "string" };
Copy after login

To iterate over both lists simultaneously, one could employ the following code:

var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach (var nw in numbersAndWords)
{
    Console.WriteLine(nw.Number + nw.Word);
}
Copy after login

Alternatively, tuples can be used to avoid named fields:

foreach (var nw in numbers.Zip(words, Tuple.Create)) 
{
    Console.WriteLine(nw.Item1 + nw.Item2);
}
Copy after login

The Zip operation streamlines the process of iterating over multiple lists, providing a concise solution for scenarios where simultaneous iteration is required.

The above is the detailed content of How Can I Iterate Through Multiple Lists Simultaneously Using a Single ForEach Loop in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template