0 Replies - 146 Views - Last Post: 17 August 2009 - 08:21 AM

#1 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1659
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Shuffle a Generic List

Posted 17 August 2009 - 08:21 AM

Description: Need a reference to the following Namespace(s)
System.Collections.GenericSnippet for shuffling a random list of type T with C#. Requires .Net Framework 3.5+. This is based on the Fisher-Yates shuffle - http://en.wikipedia....r-Yates_shuffle
/// <summary>
/// method for shuffling a generic list of type T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">the list we wish to shuffle</param>
public static void ShuffleGenericList<T>(IList<T> list)
{
    //generate a Random instance
    Random rnd = new Random();
    //get the count of items in the list
    int i = list.Count();
    //do we have a reference type or a value type
    T val = default(T);

    //we will loop through the list backwards
    while (i >= 1)
    {
        //decrement our counter
        i--;
        //grab the next random item from the list
        var nextIndex = rnd.Next(i, list.Count());
        val = list[nextIndex];
        //start swapping values
        list[nextIndex] = list[i];
        list[i] = val;
    }
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1