PROWAREtech

articles » current » dot-net » randomize-a-list

.NET: How to Randomize the Order of a List and Optional Parallel List

Using C#, randomize or shuffle a list, and optionally, a second, parallel list.

Shuffle a list or a list and its parallel list to randomize the order of data.


void ShuffleList<T>(IList<T> list1, IList<T>? list2 = null) // list2 is parallel to list1, it is an optional parameter
{
	Random rand = new Random();
	for(int i = list1.Count; i > 1;)
	{
		i--;

		int r = rand.Next(i + 1);

		T value = list1[r];
		list1[r] = list1[i];
		list1[i] = value;

		if (list2 != null)
		{
			value = list2[r];
			list2[r] = list2[i];
			list2[i] = value;
		}
	}
}

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT