foxt
foxt

Reputation:

Looping through an array without throwing exception

Say I have an array of values:

string[] text = new string[] { "val1", "val2", "val3", "val4", "val5" };

Then I have a basic loop:

for (int i = 0; i <= 30; i++)
{
    Console.WriteLine(i + " = " + text[i])
}

Obviously, this will cause an out of bounds exception, so what I want to do is when the counter reaches the upper bound of the array then go back to the start.

So

0 = val1    
1 = val2    
2 = val3    
3 = val4    
4 = val5    
5 = val1    
6 = val2    
7 = val3    
etc..

Upvotes: 2

Views: 987

Answers (7)

Paige Ruten
Paige Ruten

Reputation: 176665

You could use the modulus operator:

Console.WriteLine(i + " = " + text[i % 5])

Upvotes: 13

Timothy Carter
Timothy Carter

Reputation: 15785

As a slightly less specific solution...

class Program
{
    static void Main(string[] args)
    {
        string[] text = new string[] { "val1", "val2", "val3", "val4", "val5" };

        int count = 0;
        foreach (string t in text.ContinuousLoopTo(30))
        {
            Console.WriteLine(count.ToString() + " = " + t);
            count++;
        }

        Console.ReadLine();
    }
}

public static class Extensions
{
    public static IEnumerable<T> ContinuousLoopTo<T>(this IList<T> list, int number)
    {
        int loops = number / list.Count;

        int i = 0;

        while (i < loops)
        {
            i++;

            foreach (T item in list)
            {
                yield return item;
            }
        }

        for (int j = 0; j < number % list.Count; j++)
        {
            yield return list[j];
        }
    }
}

Upvotes: 2

MK_Dev
MK_Dev

Reputation: 3333

Shouldn't it be:

Console.WriteLine(i + " = " + text[i % text.length])

?

Upvotes: 2

Mark Brittingham
Mark Brittingham

Reputation: 28865

The writeline should be:

Console.WriteLine(i + " = " + text[i%5]);

Upvotes: 1

Jim Mischel
Jim Mischel

Reputation: 134005

Take the modulus of the array length:

for (int i = 0; i < 30; ++i)
{
    Console.WriteLine(i + " = " + text[i % text.Length]);
}

Upvotes: 12

Al W
Al W

Reputation: 7713

what? like forever?

bool run = true;
int i = 0;
string[] text = new string[] {"val1", "val2", "val3", "val4", "val5"};
while(run)
{
   Console.WriteLine(i + " = " + text[i])
   i++;
   if(i>=text.Length) i=0;
}

Upvotes: 1

Adam Ralph
Adam Ralph

Reputation: 29956

Try

for(int i=0;i<=30;i++)
{
    Console.WriteLine(i + " = " + string[i % 5])
}

Upvotes: 5

Related Questions