How to iterate over two arrays at once?

后端 未结 6 1286
我在风中等你
我在风中等你 2020-12-14 20:44

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 list

6条回答
  •  盖世英雄少女心
    2020-12-14 21:24

    Use IEnumerator for both would be nice

    var currentValues = currentRow.Split(separatorChar);
    using (IEnumerator valueEnum = currentValues.GetEnumerator(), columnEnum = columnList.GetEnumerator()) {
        while (valueEnum.MoveNext() && columnEnum.MoveNext())
            valueMap.Add(columnEnum.Current, valueEnum.Current);
    }
    

    Or create an extension methods

    public static IEnumerable Zip(this IEnumerable source, IEnumerable other, Func selector) {
        using (IEnumerator sourceEnum = source.GetEnumerator()) {
            using (IEnumerator otherEnum = other.GetEnumerator()) {
                while (sourceEnum.MoveNext() && columnEnum.MoveNext())
                    yield return selector(sourceEnum.Current, otherEnum.Current);
            }
        }
    }
    

    Usage

    var currentValues = currentRow.Split(separatorChar);
    foreach (var valueColumnPair in currentValues.Zip(columnList, (a, b) => new { Value = a, Column = b }) {
        valueMap.Add(valueColumnPair.Column, valueColumnPair.Value);
    }
    

提交回复
热议问题