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

后端 未结 6 1176
情深已故
情深已故 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:44

    Short answer is no you can't.

    Longer answer is that is because foreach is syntactic sugar - it gets an iterator from the collection and calls Next on it. This is not possible with two collections at the same time.

    If you just want to have a single loop, you can use a for loop and use the same index value for both collections.

    for(int i = 0; i < collectionsLength; i++)
    {
       list1[i];
       list2[i];
    }
    

    An alternative is to merge both collections into one using the LINQ Zip operator (new to .NET 4.0) and iterate over the result.

提交回复
热议问题