New short answer
Starting from the moment when Ilya Kogan ceased to exist, itβs completely correct after Eric Lippert found the error:
var methods = new Action[10]; var rng = new Random(); var shuffled = methods.Select(m => Tuple.Create(rng.Next(), m)) .OrderBy(t => t.Item1).Select(t => t.Item2); foreach (var action in shuffled) { action(); }
Of course, this does a lot behind the scenes. The method below should be much faster. But if LINQ is fast enough ...
Old answer (much longer)
After stealing this code from here :
public static T[] RandomPermutation<T>(T[] array) { T[] retArray = new T[array.Length]; array.CopyTo(retArray, 0); Random random = new Random(); for (int i = 0; i < array.Length; i += 1) { int swapIndex = random.Next(i, array.Length); if (swapIndex != i) { T temp = retArray[i]; retArray[i] = retArray[swapIndex]; retArray[swapIndex] = temp; } } return retArray; }
the rest is easy:
var methods = new Action[10]; var perm = RandomPermutation(methods); foreach (var method in perm) {
source share