使用foreach循环迭代两个列表

我有两个清单

List a = new List(); List b = new List(); 

现在我想迭代两个列表的元素。 我可以通过为每个列表编写一个foreach循环来做到这一点。 但也可以这样做吗?

 foreach(object o in a, b) { o.DoSomething(); } 

如果像这样的东西可能会很好:

 foreach (object o in a && b) { o.DoSomething(); } 

 foreach(object o in a.Concat(b)) { o.DoSomething(); } 

如果你想单独遍历它们,那么你可以像已经指出的那样使用Enumerable.Concat

如果你想同时遍历两个列表,从循环中的每个列表访问一个元素,那么在.NET 4.0中有一个可以使用的方法Enumerable.Zip

 int[] numbers = { 1, 2, 3, 4 }; string[] words = { "one", "two", "three" }; var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second); foreach (var item in numbersAndWords) { Console.WriteLine(item); } 

结果:

 1个
 2两
 3三
 foreach(object o in a.Concat(b)) { o.DoSomething(); } 

这是你可以做到的另一种方式:

 for (int i = 0; i < (a.Count > b.Count ? a.Count : b.Count); i++) { object objA, objB; if (i < a.Count) objA = a[i]; if (i < b.Count) objB = b[i]; // Do stuff } 

如果你想同时迭代两个相同长度的列表(特别是在测试中比较两个列表的场景),我认为for循环更有意义:

 for (int i = 0; i < list1.Count; i++) { if (list1[i] == list2[i]) { // Do something } }