The general purpose of this method is to randomly display a batch of data to be displayed, and I wrote this method at the beginning, which is also the practice of copying the QQ password to ask questions.
The original statement is as follows:
public static List<int> GetRandomList(this int maxValue) { Random rd = new Random(); List<int> list = new List<int>(); while (list.Count != maxValue) { int tempInt = rd.Next(maxValue); if (!list.Contains(tempInt)) { list.Add(tempInt); } } return list; }
Such a random sequence can be obtained, but there will certainly be some repeated useless (the generated random number repeats, and the number of repetitions cannot be determined), and the more existing sequences, the more repeated the number of times, the more random maxValue appears in extreme cases, generally maxValue + N times (N is generally more than maxValue)
I have nothing to do recently. I sorted out the general method previously written and optimized this method. The new method is as follows:
/// <Summary> /// generate a random sequence with the maximum length within the maximum value range. For example, if the maximum value is 6, the random sequence 0, 1, 2, 3, list /// </summary> /// <param name = "maxValue"> </param> /// <returns> </returns> public static List <int> GetRandomList (this int maxValue) {if (maxValue = 0) {return null;} // logical description: generate a tempList from 0 to maxValue. // then random generates maxValue once --, index the integer generated by random, add it to returnList, and remove maxValue = Math from tempList. abs (maxValue); // prevents negative List <int> tempList = new List <int> (); for (int I = 0; I <maxValue; I ++) {tempList. add (I) ;}random rd = new Random (); List <int> returnList = new List <int> (); while (maxValue> 0) {int tempInt = 0; if (maxValue> 1) // when maxValue is 1, no random operation is performed, because there is a number left, and no random {tempInt = rd. next (maxValue);} returnList. add (tempList [tempInt]); tempList. removeAt (tempInt); maxValue --;} return returnList ;}
This method first traverses a temporary List <int> to store all fields smaller than maxValue, and then uses this maxValue as the seed to generate a random number, then the random number is used as the index to retrieve the corresponding Index Integer from the temporary List and put it into the returnList. Then, the integer is removed from the temporary List.
The advantage of the second method is that there will be no repeated useless work, just random maxValue-once