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...
private List<string> MixList(List<string> inputList) { List<string> randomList = new List<string>(); if (inputList.Count == 0) return randomList;
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 }
//clean up inputList.Clear(); inputList = null; r = null;
return randomList; //return the new random list }
The C# function is written for a List<> of string types. To modify it to another data type or object, change all the List<string> occurances to List<[your type here]>.
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. The result is a randomized array list in C#.