C# Programming > Data

C# Shuffle Array

Shuffle List

Unfortunately there is no automatic way to randomize, or shuffle, an array in C#.

Yet all the pieces needed to mix a list randomly are already there. C#.NET comes with a built-in Random class, which may not be true random but works fine. C#.NET also comes with great support for strongly-typed array lists.

The C# Code

private List<E> ShuffleList<E>(List<E> inputList)
{
     List<E> randomList = new List<E>();

Random r = new Random(); int randomIndex = 0; while (inputList.Count > 0) { randomIndex = r.Next(0, inputList.Count); //Choose a random object in the list randomList.Add(inputList[randomIndex]); //add it to the new, random list inputList.RemoveAt(randomIndex); //remove to avoid duplicates }

return randomList; //return the new random list }

Some Thoughts

The C# function is written using generics so it will work on any List object.

As far as the logic of the function goes, it is quite simple. The C# function copies the original list into a new list, adding the elements in random order. It is a pretty simple way to shuffle a list. The result is a randomized array list in C#.

You might notice that this is not too efficient in terms of memory. A more memory efficient way is to do an in-place list shuffle.

Back to C# Article List