Using foreach loop to iterate through two lists

后端 未结 5 1745
攒了一身酷
攒了一身酷 2021-02-12 15:39

I have two lists

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


Now i want to iterate throug

相关标签:
5条回答
  • 2021-02-12 16:19

    If you want to iterate through them individually then you can use Enumerable.Concat as has already been pointed out.

    If you want to iterate over both lists simultaneously, having access to one element from each inside your loop, then in .NET 4.0 there is a method Enumerable.Zip that you can use.

    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);
    }
    

    Result:

    1 one
    2 two
    3 three
    
    0 讨论(0)
  • 2021-02-12 16:28
    foreach(object o in a.Concat(b)) {
     o.DoSomething();
    }
    
    0 讨论(0)
  • 2021-02-12 16:34

    If you want to simultaneously iterate over two Lists of the same length (specially in the scenarios like comparing two list in testing), I think for loop makes more sense:

    for (int i = 0; i < list1.Count; i++) {
        if (list1[i] == list2[i]) {
            // Do something
        }
    }
    
    0 讨论(0)
  • 2021-02-12 16:36
    foreach(object o in a.Concat(b)) {
     o.DoSomething();
    }
    
    0 讨论(0)
  • 2021-02-12 16:36

    This is another way you could do it:

    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
    }
    
    0 讨论(0)
提交回复
热议问题