Простая модификация принятого ответа , который возвращает новый список вместо работы на месте и принимает более общий IEnumerable
, как это делают многие другие методы Linq.
private static Random rng = new Random();
///
/// Returns a new list where the elements are randomly shuffled.
/// Based on the Fisher-Yates shuffle, which has O(n) complexity.
///
public static IEnumerable Shuffle(this IEnumerable list) {
var source = list.ToList();
int n = source.Count;
var shuffled = new List(n);
shuffled.AddRange(source);
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = shuffled[k];
shuffled[k] = shuffled[n];
shuffled[n] = value;
}
return shuffled;
}