Regarding random function in asp.net c#
Hi i want random no. of questions. For that i used random function 开发者_如何转开发in asp.net but questions gets repeating. How i can get non repeated questions. C#. Thank you.
The problem with Random is very often the following:
The following code will very often return a very 'non-random' sequence of numbers
for(int j = 0; j<100; j++)
{
Random rnd = new Random();
int i = rnd.Next(1, 5);
Console.WriteLine(i);
}
Whereas the following will create a more randomized distribution of numbers:
Random rnd = new Random();
for(int j = 0; j<100; j++)
{
int i = rnd.Next(1, 5);
Console.WriteLine(i);
}
A different approach to generating a random number could be achieved using Linq:
var randomNumber = Enumerable.Range(1, 10).OrderBy(g => Guid.NewGuid()).First();
This method first creates a list of numbers (in this example from 1 to 10), and then orders that list by creating a Guid. This shuffles the list so that the First() will be kind of random. I often rely on this method to get a random number instead of using the Random-class.
UPDATE
Let's say you want 10 unique random numbers from a list of 100 random numbers. Using the linq-expression you would do:
List<int> tenRandomNumbers = Enumerable.Range(1, 100).OrderBy(g => Guid.NewGuid()).Take(10);
Now you should be able to go through the list of tenRandomNumbers
.. They should be unique and random.
UPDATE 2
Take a look at this explanation of the .Take(int) method: http://msdn.microsoft.com/en-us/vcsharp/aa336757#TakeSimple
The code above will return a list of 10 numbers selected randomly from a collection of 100 numbers. What you want to do next is simply:
foreach(int i in tenRandomNumbers){
// code to fetch your question based on int i
}
Hope this helps
精彩评论