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
Mary-Kate OlsenOriginal
2025-01-03 22:08:41800browse

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" };

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);
}

Alternatively, tuples can be used to avoid named fields:

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

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:
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