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