Published on: 15 Oct, 2019

How to shuffle list items in c#

Tumblr Digg Google Plus

If you have a list of objects and want to shuffle the list. You can easily do that in C#. So why do you need to shuffle a list?

Well, consider if you have a site and want to display a list of random latest articles, this suffle method would be really useful.

Here is the full code in C#.

public static void ShuffleList<T>(IList<T> objList)
{
	Random rnd = new Random();
	int totalItem = objList.Count;
	T obj;
	while (totalItem >= 1)
	{
		totalItem -= 1;
		int nextIndex = rnd.Next(totalItem, objList.Count);
		obj = objList[nextIndex];
		objList[nextIndex] = objList[totalItem];
		objList[totalItem] = obj;
	}
}

Let's say we have a class called CustomerInfo. It will contain two properties which will be the FirstName and LastName.

public class CustomerInfo{
	public string FirstName { get; set; }
	public string LastName { get; set; }
}

Below is an example we declare a variable contains of a list of this item.

var customerList = new List<CustomerInfo>();
customerList.Add(new CustomerInfo() { FirstName = "Jack", LastName = "Lee" });
customerList.Add(new CustomerInfo() { FirstName = "Bella", LastName = "Mariam" });
customerList.Add(new CustomerInfo() { FirstName = "Terry", LastName = "White" });

ShuffleList<CustomerInfo>(customerList);

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.