Generate unique random numbers in C#
In the development of applications that need to generate random unique numbers, developers often encounter problems with the System.Random class. Even if you use DateTime.Now.Ticks as a seed, there may still be duplicate numbers.
Solve duplicate value problem
System.Random.Next() itself does not guarantee the uniqueness of the generated numbers. When combined with a narrower range (e.g. 0 to 10), the probability of encountering duplicate values is higher.
Alternative: List Maintenance
To overcome this limitation, a more robust approach is to maintain a list of generated numbers. Duplication can be avoided by checking whether the potential number already exists in the list.
The following is a modified implementation using this strategy:
<code class="language-csharp">public Random a = new Random(); public List<int> randomList = new List<int>(); int MyNumber = 0; private void NewNumber() { MyNumber = a.Next(0, 10); if (!randomList.Contains(MyNumber)) randomList.Add(MyNumber); }</code>
This approach ensures the creation of truly unique values by maintaining a list of generated numbers and filtering out duplicates.
The above is the detailed content of How to Generate Non-Repeating Random Numbers in C#?. For more information, please follow other related articles on the PHP Chinese website!