MarkusParker
MarkusParker

Reputation: 1596

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.

Upvotes: 3

Views: 107

Answers (3)

MarkusParker
MarkusParker

Reputation: 1596

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

Upvotes: 1

ProgrammingLlama
ProgrammingLlama

Reputation: 38737

You could just write it like this:

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

Try it online

SharpLab

Upvotes: 7

SomeBody
SomeBody

Reputation: 8743

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

Upvotes: 3

Related Questions