在c#中填充0-9之间的uniqe随机数的数组

我想用c#中的0-9之间的唯一随机数填充我的数组我试试这个函数:

IEnumerable UniqueRandom(int minInclusive, int maxInclusive) { List candidates = new List(); for (int i = minInclusive; i  1) { int index = rnd.Next(candidates.Count); yield return candidates[index]; candidates.RemoveAt(index); } } 

我这样使用它:

 for (int i = 0; i < 3; i++) { page[i] = UniqueRandom(0, 9); } 

但是我得到了错误:

 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'int' 

我还添加了这个名称空间:

 using System.Collections.Generic; 

我只是不知道如何将函数输出转换为int …请帮助我…谢谢…

使用Fischer-Yates shuffle做这样的事情要好得多:

 public static void Shuffle(this Random rng, IList list) { int n = list.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } 

用法:

 var numbers = Enumerable.Range(0, 10).ToList(); // 0-9 inclusive var rng = new Random(); rng.Shuffle(numbers); int[] page = numbers.Take(3).ToArray(); 

您的方法返回一个可枚举,但您尝试分配一个值。 一步分配所有值:

 int[] page = UniqueRandom(0, 9).Take(3).ToArray(); // instead of your loop 

编辑 :从您的评论中,我判断您可能已经复制了您向我们展示的代码,而不理解它。 也许你想用可能重复的随机数填充你的数组(例如1, 6, 3, 1, 8, ... )? 您当前的代码仅使用每个值一次(因此名称唯一 ),因此您无法使用它填充大于10的数组。

如果您只想要简单的随机数,则根本不需要这种方法。

 var rnd = new Random(); // creates an array of 100 random numbers from 0 to 9 int[] numbers = (from i in Enumerable.Range(0, 100) select rnd.Next(0, 9)).ToArray(); 

你可以这样做:

 int i = 0; foreach (int random in UniqueRandom(0, 9).Take(3)) { page[i++] = random; } 

我的arrays太大了,我需要很多随机数……当我用的时候

  int[] page = UniqueRandom(0, 9).Take(arraysize).ToArray(); 

它给了我9个独特的随机数..

我收到此错误(例如对于arraysize = 15):

 index was outside of bounds of array 

我怎么能有一个在0-9之间有太多随机数的数组而不重复?