Skip to main content

Uses a simple in-place algorithm with a pseudorandom number generator to randomly order the elements inside a C# list or array. The function uses generics to make it compatible with any object type.

public static class Shuffle
{
    private static Random random = new Random();

    public static void ShuffleList<E>(IList<E> list)
    {
        if (list.Count > 1)
        {
            for (int i = list.Count - 1; i >= 0; i--)
            {
                E tmp = list[i];
                int randomIndex = random.Next(i + 1);

                //Swap elements
                list[i] = list[randomIndex];
                list[randomIndex] = tmp;
            }
        }
    }
}