可能重复:
C# 中的随机数生成器 - 唯一值
我正在尝试编写一个生成随机数的 C# 程序,检查这个数字是否在我的数组中,如果是,重复生成数字,否则将此数字插入[i]我的数组的插槽中。
到目前为止,这是我的代码:
        int check = 0;
        Random rand = new Random();
        int[] lotto = new int[6];
        for (int i = 0; i < lotto.Length; )
        {
            check = rand.Next(1, 41);
            while (!(lotto.Contains(check)))
            {
                lotto[i] = check;
                i++;
            }
            Console.WriteLine("slot " + i + " contains " + check);
        }
        Console.Read();
    }
更新:谢谢想通了,用while替换了if :)