Generic List Shuffler in C#

Generic List Shuffler in C#

Added by Nasir Mahmood updated on Friday, November 17, 2017

Problem:

Following is small snippet which is the implementation of Fisher–Yates shuffle in csharp. This is generic extension method so we can use it for any type of list.

public static void Shuffle<T>(this IList<T> list)
{
    Random rnd = new Random();
    int icount = list.Count;
    while (icount > 1)
    {
        icount--;
        int index = rnd.Next(icount);
        T item = list[index];
        list[index] = list[icount];
        list[icount] = item;                
    }
}
                

Usage:

IList<int> list = new List<int>() { 1,2,3,4,5,7,9,6,0 };
list.Shuffle();
                

Related Tags

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected