Shuffle a List

Given a list, how can one randomly shuffle it? Like so:

private static IEnumerable<T> ShuffleList<T>(IList<T> list) {
  var length = list.Count;

  var random = new RNGCryptoServiceProvider();
  var data = new byte[length];

  var numbers = Enumerable.Range(0, length).ToList();
  var shuffledIndices = numbers.OrderBy(x => data[x]).ToArray();

  foreach (var index in shuffledIndices) {
    yield return list[index];

Note the use of RNGCryptoServiceProvider rather than using the Random class, which makes this code much more complicated due to the lack of a Next() method. However, it is cryptographically more sound.
Also, note the Range method of Enumerable to generate a sequence of numbers, which is a function I’m often needing and always forgetting exists (like std::iota in C++).

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>