Shuffling a Generic List

Using the Fisher Yates Shuffle, the following was written by Rob Thijssen which I found pretty useful. He has made it an extension method which makes it simpler and pretty effective.

public static void Shuffle<T>(this IList<T> list)
    RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
    int n = list.Count;
    while (n > 1)
        byte[] box = new byte[1];

        do provider.GetBytes(box);
            while (!(box[0] < n * (Byte.MaxValue / n)));

        int k = (box[0] % n);
        T value = list[k];
        list[k] = list[n];
        list[n] = value;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s