我想为我的列表框提供 6 个不相等的随机数。
private void Button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
int[] numbers = new int[5];
Random rnd = new Random();
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = rnd.Next(1, 50);
if (Array.IndexOf(numbers, i) == -1)
{
listBox1.Items.Add(numbers[i]);
}
}
}
我不知道我对这段代码犯了什么错误。
问题是你的 for 循环会继续增加其索引器,即使你没有找到唯一数字,你的数组会立即填充而不检查该数字是否已存在。通过这种方式,您有一个列表,该列表有时包含的项目(唯一(少于数字数组(重复项(。
在这种情况下,最好的方法是使用带有显式索引器的 while 循环,而不是 for 循环,当您找到唯一数字时,该循环将递增,直到它到达数组中的最后一个位置
int[] numbers = new int[6];
Random rnd = new Random();
// First position in the array to fill
int index = 0;
while(index < number.Length)
{
int number = rnd.Next(0, 50);
if (!numbers.Contains(number))
{
// OK we don't have it add to the array and to the list
numbers[index] = number;
listBox1.Items.Add(numbers[index]);
// Point to the next position to fill
index++;
}
}
现在还有一种不同且非常优雅的方法,可以使用一些 linq 来做同样的事情:
var indexes = Enumerable.Range(1, 50).ToList();
Random rnd = new Random();
int[] numbers = indexes.OrderBy(x => rnd.Next()).Take(6).ToArray();
但是,您需要一个循环来将数字数组添加到列表中,并且正如下面的评论中所指出的,它可能不是很有效