Randomize a List<T> C#

Last Updated On Wednesday 22nd Sep 2021

c# shuffle list

Example 1: c# randomize a list

	private static Random rng = new Random();  

public static void Shuffle<T>(this IList<T> list)  
{  
    int n = list.Count;  
    while (n > 1) {  
        n--;  
        int k = rng.Next(n + 1);  
        T value = list[k];  
        list[k] = list[n];  
        list[n] = value;  
    }  
}
	

Usage

	List<Product> products = GetProducts();
products.Shuffle();