Reputation: 1596
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
Reputation: 1596
.NET 6 allows to omit the second parameter like listA.Zip(listB)
(see here).
Upvotes: 1
Reputation: 38737
You could just write it like this:
foreach (var (a,b) in listA.Zip(listB, ValueTuple.Create))
Upvotes: 7
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