How to iterate through two collections of the same length using a single foreach

后端 未结 6 1208
情深已故
情深已故 2020-12-29 22:23

I know this question has been asked many times before but I tried out the answers and they don\'t seem to work.

I have two lists of the same length but not the same

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-29 22:27

    foreach(var tup in list1.Zip(list2, (i1, i2) => Tuple.Create(i1, i2)))
    {
      var listItem1 = tup.Item1;
      var listItem2 = tup.Item2;
      /* The "do stuff" from your question goes here */
    }
    

    It can though be such that much of your "do stuff" can go in the lambda that here creates a tuple, which would be even better.

    If the collections are such that they can be iterated, then a for() loop is probably simpler still though.

    Update: Now with the built-in support for ValueTuple in C#7.0 we can use:

    foreach ((var listitem1, var listitem2) in list1.Zip(list2, (i1, i2) => (i1, i2)))
    {
        /* The "do stuff" from your question goes here */
    }
    

提交回复
热议问题