Csharp/C#教程:使用foreach循环迭代两个列表分享


使用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循环更有意义:

上述就是C#学习教程:使用foreach循环迭代两个列表分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1010383.html

(0)
上一篇 2021年12月30日
下一篇 2021年12月30日

精彩推荐