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

1.1k Views Asked by At

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.

4

There are 4 best solutions below

1
Igor On BEST ANSWER

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

0
Zeph On

You can use the modulus operator which "computes the remainder after dividing its first operand by its second."

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

    for (int i = 0; i < 99; i++)
    {
        var j = i % 6;
        Console.WriteLine(assignments[j]);
    }
}

0 % 6 = 0
1 % 6 = 1
...
6 % 6 = 0
7 % 6 = 1   
... etc.
0
wctiger On

How about using mod

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

        for (int i = 0; i < 99; i++)
        {
            Console.WriteLine(assignments[i%6]);
        }
2
Tim Schmelter On

The obligatory LINQ solution, this extension comes in handy:

public static IEnumerable<T> RepeatIndefinitely<T>(this IEnumerable<T> source)
{
    while (true)
    {
        foreach (var item in source)
        {
            yield return item;
        }
    }
}

Now your task is very easy and readable:

var allAssignments = assignments.RepeatIndefinitely().Take(99);

You can use a foreach-loop with Console.WriteLine or build a string:

string result1 = string.Concat(allAssignments);
string result2 = string.Join(Environment.NewLine, allAssignments)