I know this question has been asked many times before but I tried out the answers and they don’t seem to work.
I have two lists of the same length but not the same type, and I want to iterate through both of them at the same time as list1[i] is connected to list2[i].
Eg:
Assuming that i have list1 (as List<string>) and list2 (as List<int>)
I want to do something like
foreach( var listitem1, listitem2 in list1, list2)
{
// do stuff
}
Is this possible?
Edit – Iterating whilst positioning at the same index in both collections
If the requirement is to move through both collections in a ‘synchronized’ fashion, i.e. to use the 1st element of the first collection with the 1st element of the second collection, then 2nd with 2nd, and so on, without needing to perform any side effecting code, then see @sll’s answer and use
.Zip()to project out pairs of elements at the same index, until one of the collections runs out of elements.More Generally
Instead of the
foreach, you can access theIEnumeratorfrom theIEnumerableof both collections using theGetEnumerator()method and then callMoveNext()on the collection when you need to move on to the next element in that collection. This technique is common when processing two or more ordered streams, without needing to materialize the streams.As others have pointed out, if the collections are materialized and support indexing, such as an
ICollectioninterface, you can also use the subscript[]operator, although this feels rather clumsy nowadays:Finally, there is also an overload of Linq’s
.Select()which provides the index ordinal of the element returned, which could also be useful.e.g. the below will pair up all elements of
collection1alternatively with the first two elements ofcollection2: