I have two lists that are of the same length, is it possible to loop through these two lists at once?
I am looking for the correct syntax to do the below
Senthil Kumar's tech blog, has a series covering implementations of (Python) Itertools for C#, including itertools.izip.
From Itertools for C# - Cycle and Zip, you have a solution for any number of iterables (not only List<T>). Note that Zip
yields an Array
on each iteration:
public static IEnumerable Zip(params IEnumerable[] iterables)
{
IEnumerator[] enumerators = Array.ConvertAll(iterables, (iterable) => iterable.GetEnumerator());
while (true)
{
int index = 0;
T[] values = new T[enumerators.Length];
foreach (IEnumerator enumerator in enumerators)
{
if (!enumerator.MoveNext())
yield break;
values[index++] = enumerator.Current;
}
yield return values;
}
}
The code gets enumerators for all the iterables, moves all enumerators forward, accumulates their current values into an array and yields the array. It does this until any one of the enumerators runs out of elements.