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);