MichaelBrowley89723
MichaelBrowley89723

Reputation: 13

Loop over two lists

I have 2 lists

How can I continue looping through List2 until I reach the end of List1? So, if I get to the end of List2 before the end of List1, start over and loop through List2 again. Once I reach the end of List1 I want to break out of both loops and continue with the rest of the program. I need a different item from each of the lists each time.

Upvotes: 1

Views: 267

Answers (1)

SomeBody
SomeBody

Reputation: 8743

Use a for loop do iterate over List1. With the modulo operator, you can make sure that your index is never bigger than the count of List2.

for (int i = 0;i < List1.Count; i++)
{
    Console.WriteLine("List1: " + List1[i]);
    Console.WriteLine("List2: " + List2[i % List2.Count]);
}

Online demo: https://dotnetfiddle.net/oL834n

Upvotes: 7

Related Questions