Randomize List items in C# (Shuffle list C#)

Lists are very useful object types in C#. A lot of times we come across requirements to sort list items. By default, we can only sort by Ascending or descending list items using Linq or Lamda but there is no default sorting order to randomize sort.

Below is a static method that can be used as an extension to Randomy shuffle list items in C#

private static Random rnd = new Random();  
public static void Shuffle<T>(this IList<T> list)  
{  
    int n = list.Count;  
    while (n > 1) {  
        n--;  
        int k = rnd.Next(n + 1);  
        T value = list[k];  
        list[k] = list[n];  
        list[n] = value;  
    }  
}
The static varible "rnd" should be defined in class level like below
Public Static Test
{
private static Random rnd = new Random();  
public static void Shuffle<T>(this IList<T> list)  
{  
    int n = list.Count;  
    while (n > 1) {  
        n--;  
        int k = rnd.Next(n + 1);  
        T value = list[k];  
        list[k] = list[n];  
        list[n] = value;  
    }  
}
}

About the author

Naveed Ul-Haq

I am a UK based technical architect. I love working with .NET based CMS, eCommerce solutions, .NET Core, DevOps, and Cloud computing. I am a Certified Episerver CMS developer, MCSD (Microsoft Certified Solution Developer) and MCP in Azure application development. I spend my free time with my family and reading books. You can contact me on [email protected]

View all posts

Leave a Reply

Your email address will not be published.