Best way to randomize an array with .NET

If you’re on .NET 3.5, you can use the following IEnumerable coolness:

Random rnd=new Random();
string[] MyRandomArray = MyArray.OrderBy(x => rnd.Next()).ToArray();    

Edit: and here’s the corresponding VB.NET code:

Dim rnd As New System.Random
Dim MyRandomArray = MyArray.OrderBy(Function() rnd.Next()).ToArray()

Second edit, in response to remarks that System.Random “isn’t threadsafe” and “only suitable for toy apps” due to returning a time-based sequence: as used in my example, Random() is perfectly thread-safe, unless you’re allowing the routine in which you randomize the array to be re-entered, in which case you’ll need something like lock (MyRandomArray) anyway in order not to corrupt your data, which will protect rnd as well.

Also, it should be well-understood that System.Random as a source of entropy isn’t very strong. As noted in the MSDN documentation, you should use something derived from System.Security.Cryptography.RandomNumberGenerator if you’re doing anything security-related. For example:

using System.Security.Cryptography;

RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
string[] MyRandomArray = MyArray.OrderBy(x => GetNextInt32(rnd)).ToArray();

static int GetNextInt32(RNGCryptoServiceProvider rnd)
    {
        byte[] randomInt = new byte[4];
        rnd.GetBytes(randomInt);
        return Convert.ToInt32(randomInt[0]);
    }

Leave a Comment