Search code examples
c#.netarraysloopsarray-population

How do i loop string array in c# more than once?


I can't quite figure it out how to loop through string array after the first initial loop has been done.

My code right now is:

    string[] assignments = new string[] {"A", "B", "C", "D", "E", "F"};

    Array.Resize<string>(ref assignments, 99);
    for (int i = 0; i < 99; i++)
    {
    Console.WriteLine(assignments[i]);
    }

However, it seems that Resizing the array doesn't accomplish much, since arrays values after the 6th value is non-existant. I need it to keep looping more then once: A B C D E F A B C D E F ... and so on, until the limit of 99 is reached.


Solution

  • Use the mod operator.

    string[] assignments = new string[] {"A", "B", "C", "D", "E", "F"};
    for (int i = 0; i < 99; i++)
    {
        Console.WriteLine(assignments[i % assignments.Length]);
    }
    

    .net fiddle