How to Shuffle a List in C# and VB.NET

To Shuffle a List in C# and VB.NET you can use the snippet below.

Sample C#

public static IList<T> ShuffleIList<T>(IList<T> inputList)
{
	var cryptoServiceProvider = new RNGCryptoServiceProvider();
	var count = inputList.Count;
	while (count > 1)
	{
		var bytes = new byte[1];
		do cryptoServiceProvider.GetBytes(bytes);
		while (!(bytes[0] < count * (Byte.MaxValue / count)));
		var index = (bytes[0] % count);
		count--;
		var input = inputList[index];
		inputList[index] = inputList[count];
		inputList[count] = input;
	}
	return inputList;
}

Sample VB.NET

Public Shared Function ShuffleIList(Of T)(inputList As IList(Of T)) As IList(Of T)
	Dim cryptoServiceProvider = New RNGCryptoServiceProvider()
	Dim count = inputList.Count
	While count > 1
		Dim bytes = New Byte(0) {}
		Do
			cryptoServiceProvider.GetBytes(bytes)
		Loop While Not (bytes(0) < count * ([Byte].MaxValue / count))
		Dim index = (bytes(0) Mod count)
		count -= 1
		Dim input = inputList(index)
		inputList(index) = inputList(count)
		inputList(count) = input
	End While
	Return inputList
End Function

Please Share us:
Please rate this snippet

2 thoughts on “How to Shuffle a List in C# and VB.NET

Leave a Reply