C# Shuffle ArrayUse Random, List and KeyValuePair structs to effectively shuffle an array.
dot net perls
Shuffle. We can shuffle an array, randomly reordering all elements, with results that are mathematically correct. Some solutions exist but do not give high-quality random results.
Imagine an array—we generate an array of completely random numbers of the same size. Then we sort the original array based on the values in the random number array.
Here we see an approach to shuffling a string array that is not an optimized shuffle. But it is mathematically random. It will not cause strange biases in your code.
And This is true because it performs all the operations together, rather than one after another.
Info The method here uses the KeyValuePair<T, V> data structure that is included in System.Collections.Generic.
Then It allocates another array containing the string elements and pairs them with a random number. Finally, it sorts.
Important We randomize the entire array all at once, which will result in consistently random results.
C# program that uses random shuffle algorithm
_random = new Random();
static string RandomizeStrings
List<KeyValuePair<int, string>> list =
new List<KeyValuePair<int, string>>();
// Add all strings from array.
// ... Add new random int each time.
foreach (string s in arr)
list.Add(new KeyValuePair<int, string>(_random.Next(), s));
// Sort the list by the random number.
var sorted = from item in list
// Allocate new string array.
string result = new string[arr.Length];
// Copy values to array.
int index = 0;
foreach (KeyValuePair<int, string> pair in sorted)
result[index] = pair.Value;
// Return copied array.
static void Main()
string arr = new string
string shuffle = RandomizeStrings
(string s in shuffle)
The code stores a Random number generator as a static field. You can call the RandomizeStrings method repeatedly and will get good results.
The current method is mathematically sound, as noted in Wikipedia. See "Comparison with other shuffling algorithms" from the link.
Info Wikipedia notes that this approach is sometimes faster in high-level languages. It is unlikely to be faster in the C# language.
Fisher-Yates shuffle: Wikipedia
A summary. We used a mathematically sound approach for shuffling an array. This method is not optimally fast. If you need performance, use an implementation of Fisher-Yates.
© 2007-2021 sam allen. send bug reports to email@example.com.