Search code examples
c#linq

Iterating two lists in a compact way


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.


Solution

  • .NET 6 allows to omit the second parameter like listA.Zip(listB) (see here).