After I’ve shown you (in this post) how to generate unique random numbers in PHP, I’ll show you now how to do the same thing in C#. If you’re wondering, for what you need different unique random numbers, you really should have a gander at the PHP-based article. Otherwise go on and take a look at the following snippet.
//Define the range of random numbers, from which //the routine should choose int smallestNumber = 1; int biggestNumber = 10; //Determine the amount of random numbers int amountOfRandomNumbers = 5; //Create a list of numbers from which the routine //shall choose the result numbers List possibleNumbers = new List(); for (int i = smallestNumber; i <= biggestNumber; i++) possibleNumbers.Add(i); //Create a list, which shall hold the result numbers List resultList = new List(); //Initialize a random number generator Random rand = new Random(); //For-loop which picks each round a unique random number for (int i = 0; i < amountOfRandomNumbers; i++) { //Generate random number int randomNumber = rand.Next(1,possibleNumbers.Count) - 1; //Use random number as index for the possible number list resultList.Add(possibleNumbers[randomNumber]); //Remove the chosen result number from possible numbers list possibleNumbers.RemoveAt(randomNumber); }