这只是一般知识:
如果我有两个,比方说,List,我想用相同的 foreach 循环迭代这两个,我们可以这样做吗?
编辑
澄清一下,我想这样做:
List<String> listA = new List<string> { "string", "string" };
List<String> listB = new List<string> { "string", "string" };
for(int i = 0; i < listA.Count; i++)
listB[i] = listA[i];
但是有一个 foreach =)
最佳答案
这被称为 Zip操作并将在 .NET 4 中得到支持。
有了它,您就可以编写如下内容:
var numbers = new [] { 1, 2, 3, 4 };
var words = new [] { "one", "two", "three", "four" };
var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach(var nw in numbersAndWords)
{
Console.WriteLine(nw.Number + nw.Word);
}
作为具有命名字段的匿名类型的替代方案,您还可以通过使用 Tuple 及其静态 Tuple.Create 帮助程序来节省大括号:
foreach (var nw in numbers.Zip(words, Tuple.Create))
{
Console.WriteLine(nw.Item1 + nw.Item2);
}
关于c# - 在 C# 中用一个 ForEach 语句迭代两个列表或数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1955766/