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

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

    This is possible using .NET 4 LINQ Zip() operator or using open source MoreLINQ library which provides Zip() operator as well so you can use it in more earlier .NET versions

    Example from MSDN:

    int[] numbers = { 1, 2, 3, 4 };
    string[] words = { "one", "two", "three" };
    
    // The following example concatenates corresponding elements of the
    // two input sequences.
    var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);
    foreach (var item in numbersAndWords)
    {
        Console.WriteLine(item);
    }
    
    // OUTPUT:
    // 1 one
    // 2 two
    // 3 three
    

    Useful links:

    • Soure code of the MoreLINQ Zip() implementation: MoreLINQ Zip.cs

提交回复
热议问题