在 C# 中使用统一的 ForEach 循环迭代多个列表
在 C# 中,可能会遇到使用单个列表同时迭代多个列表的情况需要 foreach 循环。本文探讨了使用 .NET 4 中引入的 Zip 操作解决此问题的方法。
Zip 操作使开发人员能够将多个序列中的元素组合到单个序列中,从而允许配对迭代。考虑以下示例:
List<string> listA = new List<string> { "string", "string" }; List<string> listB = new List<string> { "string", "string" };
要同时迭代两个列表,可以使用以下代码:
var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w }); foreach (var nw in numbersAndWords) { Console.WriteLine(nw.Number + nw.Word); }
或者,可以使用元组来避免命名字段:
foreach (var nw in numbers.Zip(words, Tuple.Create)) { Console.WriteLine(nw.Item1 + nw.Item2); }
Zip 操作简化了多个列表迭代的过程,为同时迭代的场景提供了简洁的解决方案必填。
以上是如何在 C# 中使用单个 ForEach 循环同时迭代多个列表?的详细内容。更多信息请关注PHP中文网其他相关文章!