Unique Random Number Generation in C#

We all know about Random function in C#, It is used to generate random no in C#. But in some case we need to generate the random no of specific range and it must be unique. So check the code.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Diagnostics;    
  4. using System.Linq;    
  5. using System.Runtime.InteropServices;    
  6. using System.Text;    
  7. using System.Threading.Tasks;    
  8.     
  9. namespace ConsoleApplication2    
  10. {    
  11.     class Program    
  12.     {    
  13.         static void Main(string[] args)    
  14.         {    
  15.             List<int> uniqueNoList = new List<int>();    
  16.             uniqueNoList = UniqueRandomNoList(50, 5);    
  17.             foreach (int no in uniqueNoList)    
  18.             {    
  19.                 Console.WriteLine(no);    
  20.             }    
  21.             Console.ReadLine();    
  22.         }    
  23.         public static List<int> UniqueRandomNoList(int maxRange, int totalRandomnoCount)    
  24.         {    
  25.     
  26.             List<int> noList = new List<int>();    
  27.             int count = 0;    
  28.             Random r = new Random();    
  29.             List<int> listRange = new List<int>();    
  30.             for (int i = 0; i < totalRandomnoCount; i++)    
  31.             {    
  32.                 listRange.Add(i);    
  33.             }    
  34.             while (listRange.Count > 0)    
  35.             {    
  36.                 int item = r.Next(maxRange);// listRange[];    
  37.                 if (!noList.Contains(item) && listRange.Count > 0)    
  38.                 {    
  39.                     noList.Add(item);    
  40.                     listRange.Remove(count);    
  41.                     count++;    
  42.                 }    
  43.             }    
  44.             return noList;    
  45.         }    
  46.     }    
  47.     
  48. }  
In above code just check the UniqueRandomNoList the function. In this function user need to pass the max range and the no of unique no to be generated.

In above first i have created a list of the specific range list. After that check the count must be zero and check the range weather the count is zero or not. while adding the value simply check the value present in the list or not.

Here is the output.

Ebook Download
View all
Learn
View all