C # method for generating random numbers without duplicates,
When using the Random class to generate a Random number, we may encounter the problem of duplicate Random numbers.
For example, if we want to generate a 6-digit Verification Code, although Random is also used, it may be 111111,999999.
This is because when the Random class is instantiated, if the Random Seed is not filled in, the pseudo-Random computation is performed using the timeline as the seed by default. When the computation speed is too fast, all the Random seed is a value.
The solution is also very simple. We will not repeat it by using the Guid hash code as the seed value. The Code is as follows:
1 public class RandomHelper 2 {3 /// <summary> 4 // generate a random code (number) of the specified digits) 5 /// </summary> 6 /// <param name = "length"> </param> 7 /// <returns> </returns> 8 public static string GenerateRandomCode (int length) 9 {10 var result = new StringBuilder (); 11 for (var I = 0; I <length; I ++) 12 {13 var r = new Random (Guid. newGuid (). getHashCode (); 14 result. append (r. next (0, 10); 15} 16 return result. toString (); 17} 18}
Done.