Jack Yasgar .NET

Just some ranting by a long time developer . . .

List<T> Shuffle / Random Order

Had a project where we needed to be able to process items in a list in random order. The implementation of the random order was a little verbose. This extension method on IList<T> works pretty well for me.

 

static readonly Random Random = new Random();

    /// <summary>
    /// This is a Shuffle extension to shuffle the order of Lists randomly
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    public static void Shuffle<T>(this IList<T> list)
    {
        int intListCount = list.Count;
        while (intListCount > 1)
        {
            intListCount--;
            int intRandom = Random.Next(intListCount + 1);
            T value = list[intRandom];
            list[intRandom] = list[intListCount];
            list[intListCount] = value;
        }
    } // Shuffle<T>(this IList<T> list)

 

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading