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

How Can I Iterate Over Two Lists Simultaneously Using a Single ForEach Loop in C#?

Barbara Streisand
Release: 2024-12-31 05:37:10
Original
639 people have browsed it

How Can I Iterate Over Two Lists Simultaneously Using a Single ForEach Loop in C#?

Iterating Two Lists with a Single ForEach Loop in C#

Zip is a C# feature introduced in .NET 4 that facilitates the iteration of multiple collections using a single loop. It achieves this by pairing elements from each collection into a single composite object, which can then be iterated over.

To illustrate, consider the following code:

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

var result = listA.Zip(listB, (a, b) => new { A = a, B = b });

foreach (var pair in result)
{
    Console.WriteLine($"{pair.A} - {pair.B}");
}
Copy after login

In the above example, the Zip method pairs elements from both listA and listB into an anonymous type that contains both values. The foreach loop then iterates over this collection of anonymous types, allowing you to access both values in each pair.

Alternatively, you can use a tuple to achieve the same result:

foreach (var pair in listA.Zip(listB, Tuple.Create))
{
    Console.WriteLine($"{pair.Item1} - {pair.Item2}");
}
Copy after login

By leveraging the Zip operation, you can easily iterate over multiple collections and combine their elements into a single composite object for efficient processing.

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

source:php.cn
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