C# Code Snippets

Shuffle Lists and Arrays

Visual C# Kicks

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.

Platform: .NET Framework 2.0

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;
            }
        }
    }
}

Back to C# Code Snippet List