循环遍历数组而不抛出异常

时间:2009-01-21 00:26:24

标签: c# arrays loops

说我有一系列值:

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

然后我有一个基本循环:

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

显然,这会导致越界异常,所以我想做的是当计数器到达数组的上限然后回到开始。

所以

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

7 个答案:

答案 0 :(得分:13)

您可以使用模数运算符:

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

答案 1 :(得分:12)

取数组长度的模数:

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

答案 2 :(得分:5)

尝试

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

答案 3 :(得分:2)

不应该是:

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

答案 4 :(得分:2)

作为一种稍微不那么具体的解决方案......

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];
        }
    }
}

答案 5 :(得分:1)

什么?喜欢永远?

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;
}

答案 6 :(得分:1)

写作应该是:

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