filling a array with uniqe random numbers between 0-9 in c#

后端 未结 4 1062
一整个雨季
一整个雨季 2020-12-07 05:58

I want to fill my array with unique random numbers between 0-9 in c# I try this function:

    IEnumerable UniqueRandom(int minInclusive, int maxIn         


        
4条回答
  •  悲&欢浪女
    2020-12-07 06:34

    Your method returns an enumerable, but you try to assign a single value. Assign all the values in one step:

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

    EDIT: From your comments, I judge that you might have copied the code you have shown us without understanding it. Maybe you want to fill your array with random numbers with repetitions possible (e.g. 1, 6, 3, 1, 8, ...)? Your current code only uses each value once (hence the name unique), so you cannot fill an array of size larger than 10 with it.

    If you just want simple random numbers, there's no need for this method at all.

    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();
    

提交回复
热议问题