22

I have two lists

List<object> a = new List<object>();
List<object> b = new List<object>();

Now i want to iterate through the elements of both list. I could do that by writing a foreach loop for each list. But is it also possible to do something like that?

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

It would also be nice if something like that would be possible:

foreach (object o in a && b) {
   o.DoSomething();
}
1
  • 3
    Do you want to iterate through them simultaneously, or first one then the other? Commented Dec 15, 2010 at 13:58

6 Answers 6

31
foreach(object o in a.Concat(b)) {
 o.DoSomething();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but what if Concat is not supported by the Collection i use?
If you are using a List<T> and .Net version 3.5 or higher you do have the Concat method. Just add using System.Linq
15

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

Comments

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

Comments

1

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
}

1 Comment

instead of (a.Count > b.Count ? a.Count : b.Count) you can use Math.Max(a.Count, b.Count)
1

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

Comments

0

Simply we can achieve using for loop

 int[] numbers = { 1, 2, 3, 4 };
    string[] words = { "one", "two", "three" };
    
     for (int i = 0; i < numbers .Count; i++)
                {
    var list1=numbers [i];
    var list 2=words[i];
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.