I want to generate unique random numbers in C#. Once a number is generated, then it must not generate again.
Loading
I want to generate unique random numbers in C#. Once a number is generated, then it must not generate again.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sandhiya PriyaPosted Jan 7, 2026, 4:17 AM
you want to generate unique random numbers in C# so that once a number is picked, it won’t repeat.
Here are a few clean approaches:
Approach 1: Use a
HashSetto Track Generated NumbersEnsures uniqueness using
HashSet.Works for any range.
If you need all numbers in a range, this can get inefficient for large ranges.
Approach 2: Shuffle a List (Best for Full Range)
Generates all numbers in range without duplicates.
Efficient if you need a complete set of unique randoms.
Uses more memory for very large ranges.
Approach 3: LINQ One-Liner (Quick & Elegant)
Concise.
Great for small sets.
Less efficient for huge ranges.
Practice
If you need all numbers in a range ? use Approach 2 (Shuffle).
If you need a few unique numbers ? use Approach 1 (HashSet).
Jignesh KumarPosted Jan 16, 2023, 7:42 AM
you can use Random calss to generate random int number in various way,
Note : Next(); has method overloading which will allow you to pass different parameter so you can use according to your requirement.
Rajesh GamiPosted Jan 16, 2023, 6:44 AM
You can create a function and add a min-max value that can generate a random number between those min max values
Vishal JoshiPosted Jan 16, 2023, 5:55 AM
Hello Naimish,
You can use the Random class to create random numbers. Please check below sample code.
Thanks
Amit MohantyPosted Jan 16, 2023, 5:36 AM
You can use the
System.Randomclass to generate random numbers in C#, and then store the generated numbers in a data structure such as aHashSetto ensure that each number is unique.Sachin SinghPosted Jan 16, 2023, 5:35 AM
check this