Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

How to generate many random various numbers?

4.27/5 (9 votes)
9 Sep 2011CPOL 16.9K  
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:


C#
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:


C#
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:


C#
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.

License

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