我知道这个问题已经被问过很多次了,但我尝试了这些答案,但它们似乎没有用。
我有两个长度相同但类型不同的列表,我想同时遍历这两个列表 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
有用的链接:
- MoreLINQ Zip() 实现的源代码:MoreLINQ Zip.cs
关于c# - 如何使用单个 foreach 遍历两个相同长度的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8518761/