Monday, 10 August 2009

Shuffle: an extension method of random uselessfulness

UPDATE: I have updated this method here: http://thegrenade.blogspot.com/2010/02/when-random-is-too-consistent.html

Have you ever needed to randomly sort a list in C#? Add this to your nifty extensions library:

  1. /// <summary>  
  2. /// Shuffles the specified list (Extension Method for any IList<T>).  
  3. /// </summary>  
  4. /// <remarks>  
  5. /// Algorithm described at: http://en.wikipedia.org/wiki/Fisher-Yates_shuffle  
  6. /// </remarks>  
  7. /// <example>list.Shuffle();</example>  
  8. public static void Shuffle<T>(this IList<T> list)  
  9. {  
  10.     Random rng = new Random();  
  11.     int n = list.Count;  
  12.     while (n > 1) {  
  13.         n--;  
  14.         int k = rng.Next(n + 1);  
  15.         T value = list[k];  
  16.         list[k] = list[n];  
  17.         list[n] = value;  
  18.     }  
  19. }  

1 comment:

Dio said...

Hi,

A simple question but what class name should I put this method in, so that it can be used in any IList ?


Thanks.
Dio