Search code examples
c#iteratorenumerator

How to iterate over two arrays at once?


I have two arrays built while parsing a text file. The first contains the column names, the second contains the values from the current row. I need to iterate over both lists at once to build a map. Right now I have the following:

var currentValues = currentRow.Split(separatorChar);
var valueEnumerator = currentValues.GetEnumerator();

foreach (String column in columnList)
{
    valueEnumerator.MoveNext();
    valueMap.Add(column, (String)valueEnumerator.Current);
}

This works just fine, but it doesn't quite satisfy my sense of elegance, and it gets really hairy if the number of arrays is larger than two (as I have to do occasionally). Does anyone have another, terser idiom?


Solution

  • if there are the same number of column names as there are elements in each row, could you not use a for loop?

    var currentValues = currentRow.Split(separatorChar);
    
    for(var i=0;i<columnList.Length;i++){
       // use i to index both (or all) arrays and build your map
    }