Iterating Multiple Lists or Arrays Simultaneously: Zip Function in C#
To efficiently iterate over multiple collections with a single foreach statement, C# provides the built-in Zip function. This operation has been available since .NET 4 and simplifies the process of pairing elements from different sequences.
To utilize the Zip function, simply invoke it on two or more collections. For instance, consider the following example with two lists:
var numbers = new [] { 1, 2, 3, 4 }; var words = new [] { "one", "two", "three", "four" };
Using the Zip function, you can create a new sequence that combines elements from both lists, resulting in a sequence of tuples:
var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
Now, you can iterate over the numbersAndWords sequence using a foreach loop:
foreach(var nw in numbersAndWords) { Console.WriteLine(nw.Number + nw.Word); }
This will print the concatenated values:
1one 2two 3three 4four
Alternatively, instead of using an anonymous type with named fields, you can also utilize Tuple and its static Tuple.Create helper:
foreach (var nw in numbers.Zip(words, Tuple.Create)) { Console.WriteLine(nw.Item1 + nw.Item2); }
The Zip function provides an elegant and efficient solution for iterating over multiple collections simultaneously in C#. It simplifies the process of combining elements from different sequences, making code more readable and maintainable.
The above is the detailed content of How Can C#'s Zip Function Simplify Iterating Over Multiple Lists Simultaneously?. For more information, please follow other related articles on the PHP Chinese website!