1

I am developing a web app on asp.net which is online exam system. now, in this i am fetching questions and answers from table on random bases. what i want to do is to ignore a number which is already generated once so that same question will not repeat. following is the code i have used. what to do here??

    Random rnd = new Random();
    int i = rnd.Next(startid, endid + 1);
    getQuestion(i);
    public void getQuestion(int no)
    {
      String str = "select * from asp_easy where no = '"+no+"'";
    }
John Saunders
  • 160,644
  • 26
  • 247
  • 397

2 Answers2

1

What I would do is create a List<int> object, containing the primary key value associated with each question in the asp_easy table (i.e. the question ID field, which looks to be no in your code).

Pick a random number from this list, remove it from the list of available numbers, then retrieve that question number from the database.

This ensures that you always get unique questions (as long as that object stays around) and should be constant time or get faster as the size of the list shrinks.

As others have mentioned you should probably tighten up your data access methods as building queries by concatenation of strings is a universally bad idea :)

Edit: Depending on how important proper randomness is to you, look into using an unbiased source of randomness. Otherwise, you may get the same questions being selected for a given set of candidate questions over larger sample sizes.

Adam James
  • 356
  • 3
  • 10
  • ok ajames . i understood what you are suggesting. thank you... and thank you everyone for the response. –  Jul 09 '14 at 14:56
  • Great, glad I was able to help. If you are happy that I have completely answered your question, I would appreciate you marking it as the answer (the green tick) when you are able. Thanks! – Adam James Jul 09 '14 at 15:26
0

Have a list of string and random variable and push each element into the list with generating a random number. that may help you.

Or following may help.

select top 10 * from [asp_easy ] order by newid()
Maharshi
  • 1,178
  • 1
  • 14
  • 37