c# - C#中如何从数组中获取随机值

标签 c# .net arrays random collections

<分区>

Possible Duplicate:
Access random item in list

我有一个包含数字的数组,我想从这个数组中获取随机元素。例如:{0,1,4,6,8,2}。我想选择 6 并将这个数字放在另一个数组中,新数组的值为 {6,....}。

我使用 random.next(0, array.length),但这给出了长度的随机数,我需要随机数组数。

for (int i = 0; i < caminohormiga.Length; i++ )
{
    if (caminohormiga[i] == 0)
    {
        continue;
    }

    for (int j = 0; j < caminohormiga.Length; j++)
    {
        if (caminohormiga[j] == caminohormiga[i] && i != j)
        {
            caminohormiga[j] = 0;
        }
    }
}

for (int i = 0; i < caminohormiga.Length; i++)
{
   int start2 = random.Next(0, caminohormiga.Length);
   Console.Write(start2);
}

return caminohormiga;

最佳答案

I use the random.next(0, array.length), but this give random number of the length and i need the random array numbers.

使用 random.next(0, array.length) 的返回值作为索引从 array 中获取值

 Random random = new Random();
 int start2 = random.Next(0, caminohormiga.Length);
 Console.Write(caminohormiga[start2]);

关于c# - C#中如何从数组中获取随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14297853/

相关文章:

c# - 使列表不可变

c# - c#中的[Parameter]属性是什么

c# - 更改时将事件附加到属性

arrays - z3 求解器中的求和数组

c# - 将int写入byte,长度为4

c# - 将文件上传到 SharePoint Online(office 365) 库调用错误

.net - WPF 堆栈面板居中对齐

c# - 基于推和基于拉的结构(如 IEnumerable<T> 和 IObservable<T>)之间有什么区别

c# - 人们在使用 Rhino Mocks 的 ASP.NET MVC 中将哪些资源用于 TDD?

c++ - GBA C++ : How to draw multiple animating pixels using arrays?