IMG-LOGO

How to shuffle list items in c#

andy - 15 Oct, 2019 3772 Views 0 Comment

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.

Related Articles

How to remove html tags from string in c#?

Sometimes you need to remove HTML tags from string to ensure there are no dangerous or malicious scripts especially when you want to store the string or data text into the database.

Free Open Source .Net CMS

Are you looking for an open source .Net CMS for your site? When we say open source it means you can get full access to the source code without having to pay a cent.