有条件地遍历数组

时间:2018-11-15 12:57:59

标签: c#

我有一个未知尺寸的数组。数组的大小将确定其他控件的颜色。数组中的前10个项目将遵循可预测的模式。看到阵列的大小可以是任意大小,而我梦想着超过100种的新颜色会很累(想象500种独特的颜色!)

如何遍历10种以上的颜色?例如array.count是11。前10个是可预测的。假设0 =红色,1 =蓝色,2 =黑色,3 =黄色10 =现在应该是红色,因为它超过10并重新开始。

例如

10 = Red 20 = Red 30=Red 40 = Red
11=blue 21=blue 31=blue 41=blue
12=black 22=black 32=black
13=yellow; 23=yellow; 33=yellow

并根据数组的大小(可以是一千)进行这样的操作。尽管使用了类似mod的工具,但对我来说还是失败了,或者我可以编写有史以来最长的IF。

最后,代码大致如下所示

for (int i = 0; i < Array.Count; i++)
{
    if (i == 0)
    {
        color = red
    }
    else if (i == 1)
    {
        color = blue
    }
    //...

1 个答案:

答案 0 :(得分:1)

正如其他人在评论中提到的那样,请使用Modulo运算符:

void Main()
{
    var controls = Enumerable.Range(1,100).Select(i => new Control()).ToArray(); //create an Control[] with 100 controls.
    var colors = new[] {"Red", "Blue", "Green", "Yellow"}; //create a string[] holding your various color values

    //assign a color to each control
    for (int i=0; i<controls.Length; i++)
    {
        controls[i].Color = colors[i % colors.Length];
    }

    //show the result
    foreach (var control in controls)
    {
        Console.WriteLine(control.Color);
    }
}

class Control 
{
    public string Color{get;set;}
}