Iterating two lists in a compact way

Viewed 63

Is there a more compact way to write a loop for iterating over two list at once than the following:

var listA = new List<string>();
var listB = new List<int>();
foreach (var (itemFromListA, itemFromListB) in listA.Zip(listB, 
        (itemFromListA, itemFromListB)=>(itemFromListA, itemFromListB)){                
   // do something with itemFromListA and itemFromListB
}

Typing (itemFromListA, itemFromListB) three times seems unnecessarily cumbersome and something like (itemFromListA, itemFromListB)=>(itemFromListA, itemFromListB) is too long for just an identity operator.

2 Answers

You could just write it like this:

foreach (var (a,b) in listA.Zip(listB, ValueTuple.Create))

Try it online

SharpLab

You could use a for loop:

for(int i = 0; i < listA.Count && i < listB.Count; i++)
 {
 Console.WriteLine(listA[i]);
 Console.WriteLine(listB[i]);
 }
Related