How to generate many random various numbers?
Use LINQ:public IEnumerable GenerateRandomSequence(int min, int max){ var rnd = new Random(); return Enumerable.Range( min, max-min ).OrderBy( n => rnd.Next() );}You'll need a reference to System.Core to use this, and a version of .NET that supports LINQ.If you're using...
Use LINQ:
public IEnumerable<int> GenerateRandomSequence(int min, int max)
{
var rnd = new Random();
return Enumerable.Range( min, max-min ).OrderBy( n => rnd.Next() );
}
You'll need a reference to System.Core
to use this, and a version of .NET that supports LINQ.
If you're using .NET 4, you can use multiple cores to parallelize it, just add ".AsParallel()
" to the end of the Range
function:
return Enumerable.Range( min, max-min ).AsParallel().OrderBy( n => rnd.Next() );
NOTE: AsParallel() is not a good way to accomplish this, as the Random class is not thread safe. For a parallel and thread safe solution, see the article mentioned in the comments below (Thanks to Richard Deeming for pointing this out! :) )
To use:
foreach(var number in GenerateRandomSequence(10,500))
{
// Do something with number
Console.WriteLine(number);
}
The above code generates a non-repeating random sequence of numbers between 10 and 500.