Randomize a List in C#
To randomize a list in C# we can loop through the list using While the index bigger than index 0, and create random number usingNext()
function and switch values of current index and generated index.Example
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<int> myValues = new List<int>(new int[] { 1, 2, 3 } );
int n = myValues.Count;
Random rng = new Random();
while (n > 1) {
n--;
int k = rng.Next(n + 1);
int currentVal = myValues[k];
myValues[k] = myValues[n];
myValues[n] = currentVal;
}
Console.WriteLine("Lists " + string.Join(", ", myValues));
}
}