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;
}
}
}