我如何在c#中多次循环字符串数组?

loading...


0

在第一个初始循环完成后,我无法弄清楚如何循环遍历字符串数组 .

我的代码现在是:

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

但是,似乎调整数组大小没有太大成效,因为第6个值之后的数组值不存在 . 我需要它继续循环一次:A B C D E F A B C D E F ...依此类推,直到达到99的极限 .

4回答

  • 6

    使用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


  • 2

    您可以使用modulus运算符"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

    强制性LINQ解决方案,这个扩展派上用场:

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

    现在您的任务非常简单易读:

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

    您可以将 foreach -loop与 Console.WriteLine 一起使用或构建一个字符串:

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

  • 2

    怎么样使用mod

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

loading...

评论

暂时没有评论!