c# - 如何使用单个 foreach 遍历两个相同长度的集合

标签 c#

我知道这个问题已经被问过很多次了,但我尝试了这些答案,但它们似乎没有用。

我有两个长度相同但类型不同的列表,我想同时遍历这两个列表 list1[i]连接到 list2[i] .

例如:

假设我有 list1(如 List<string>)和 list2(如 List<int>)

我想做类似的事情

foreach( var listitem1, listitem2 in list1, list2)
{
   // do stuff
}

这可能吗?

最佳答案

这可以使用 .NET 4 LINQ Zip() operator或使用开源 MoreLINQ library它还提供 Zip() 运算符,因此您可以在更早的 .NET 版本中使用它

示例来自 MSDN :

int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };

// The following example concatenates corresponding elements of the
// two input sequences.
var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);
foreach (var item in numbersAndWords)
{
    Console.WriteLine(item);
}

// OUTPUT:
// 1 one
// 2 two
// 3 three

有用的链接:

关于c# - 如何使用单个 foreach 遍历两个相同长度的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8518761/

相关文章:

c# - C# 中的 antlr4 parser.prog

c# - 如何在 WPF 中创建具有 Microsoft Web 应用程序样式的菜单

c# - UrlRewriter.net 将非 www 重定向到 www

c# - 使用匿名委托(delegate)时如何退出 List<string>.ForEach 循环?

c# - NativeWindow WndProc 未接收消息

c# - 本地数据库 Windows Phone 7

c# - 将谓词作为参数传递 c#

c# - XML-(反)序列化整数的列表属性作为简单的分隔符分隔序列

c# - DataGridView 中没有重复项

c# - 将类放在不同的文件夹中但在相同的 namespace 下调用它们?