Looping through 2 Lists at once

前端 未结 7 451

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



        
7条回答
  •  醉酒成梦
    2021-01-31 11:07

    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.

提交回复
热议问题