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))
{
Console.WriteLine(number);
}
The above code generates a non-repeating random sequence of numbers between 10 and 500.
Started programming on a Commodore Vic-20 at 6 years old. Never really stopped since then. Fluent in x86 Assembly, C++ (ATL & MFC), C# (ASP.NET/WF/WPF/Silverlight), HTML, & Javascript. Really excited at the fast pace at which new technology is released.