How to iterate over two arrays at once?

后端 未结 6 1287
我在风中等你
我在风中等你 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:13

    In a functional language you would usually find a "zip" function which will hopefully be part of a C#4.0 . Bart de Smet provides a funny implementation of zip based on existing LINQ functions:

    public static IEnumerable Zip(
      this IEnumerable first, 
      IEnumerable second, 
      Func func)
    {
      return first.Select((x, i) => new { X = x, I = i })
        .Join(second.Select((x, i) => new { X = x, I = i }), 
        o => o.I, 
        i => i.I, 
        (o, i) => func(o.X, i.X));
    }
    

    Then you can do:

      int[] s1 = new [] { 1, 2, 3 };
      int[] s2 = new[] { 4, 5, 6 };
      var result = s1.Zip(s2, (i1, i2) => new {Value1 = i1, Value2 = i2});
    

提交回复
热议问题