2

假设我有一个值数组:

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..
4

7 回答 7

13

您可以使用模数运算符:

Console.WriteLine(i + " = " + text[i % 5])
于 2009-01-21T00:29:12.320 回答
12

取数组长度的模数:

for (int i = 0; i < 30; ++i)
{
    Console.WriteLine(i + " = " + text[i % text.Length]);
}
于 2009-01-21T00:34:53.340 回答
5

尝试

for(int i=0;i<=30;i++)
{
    Console.WriteLine(i + " = " + string[i % 5])
}
于 2009-01-21T00:29:46.517 回答
2

不应该是:

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

?

于 2009-01-21T00:40:48.617 回答
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];
        }
    }
}
于 2009-01-21T00:58:50.123 回答
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;
}
于 2009-01-21T00:29:55.970 回答
1

写行应该是:

Console.WriteLine(i + " = " + text[i%5]);
于 2009-01-21T00:31:37.993 回答