Click here to Skip to main content
15,888,112 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All,

I want to generate random number in specified range. These generated number should not be present in student list as member variable(rollno) shown below
Class Student
{
   int rollno;
   string name;
}

// List to hold Student[]
List<Student> studentList = new List<Student>();


// Now here i want to use linq to generate random number in range of 1 to 300 which is not present in studentList as rollno. 
Posted
Comments
Mehdi Gholam 3-May-12 2:25am    
Have you tried Random()? Why LINQ, it doesn't make sense?
LaxmikantYadav 3-May-12 2:52am    
I can use Random(), but how to ensure that generated number is not exist in list(i.e Student.rollno).
VJ Reddy 4-Jun-12 4:48am    
Thank you for accepting the solution :)

There are two basic ways to do this task:

1) Generate a random number.
1a) Check if it is in the list.
1b) If it is, repeat from (1)
or
2) Generate a list of numbers between 1 and 300 in a List (call it availableNumbers)
2a) Remove all numbers in the Student list from availableNumbers (or don't add them in the first place)
2b) When you want a student number, generate a random number for 0 to availableNumbers.Length - 1
2c) Use this number as an index into availableNumbers. This gives you the random number you want.
2d) Remove the number from availableNumbers.

The first is simpler to code, but can take a lot of time - and the chances of a long time increase as the number of used numbers increases. It does not have any initial one-of setup time cost.
The second if slightly harder to code, but is consistent in how long it takes to provide a number. There is a one-off cost to set up the availableNumbers list in the first place.

Neither of these need the sledgehammer that is Linq.
 
Share this answer
 
The following code can be used to generate a random number and to check whether it is existing in the List using LINQ.
In random.Next 301 is taken as it returns A 32-bit signed integer greater than or equal to minValue and less than maxValue; as explained here
Random.Next Method (Int32, Int32)[^]
C#
void Main()
{
    List<student> studentList = new List<student>();
    
    Random random = new Random(1);
    for(int i=1; i<311; i++){
        while (studentList.Count < 300) {
            int nextNumber = random.Next(1,301);
            //FirstOrDefault returns null if the nextNumber is not found 
            //as Student is a reference type
            if (studentList.FirstOrDefault (s => s.rollno == nextNumber) == null){
            	studentList.Add(new Student(){rollno=nextNumber});
            	break;
            }
        }
    }
    //Test whether only up to 300 numbers generated, as 310 is given for loop
    foreach(Student student in studentList.OrderBy (s => s.rollno )){
        Console.WriteLine (student.rollno);
    }
}

class Student
{
    public int rollno;
    public string name;
}
 
Share this answer
 
v4
Here may be a cleaner solution:

XML
public List<int> GetRandom(List<int> studentIDs, int count, int maxValue)
{
    List<int> found = new List<int>();
    Random generator = new Random();

    while (found.Count() < count)
    {
        int num = generator.Next(maxValue);
        if (studentIDs.Any(i => i == num))
            found.Add(num);
    }
    return found;
}
 
Share this answer
 
Comments
LaxmikantYadav 4-Jun-12 5:03am    
Thanks :)
You may find an implementation of the second algorithm proposed by OriginalGriff in my tip: Random extraction of 5 cards from a deck[^] (sorry is C++).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900