I have a list of objects and I want to reorder them randomly on each request. What is the best way of doing this?
How about some kind of Knuth-Fisher-Yates shuffle algorithm ?
for (int i = cards.Length - 1; i > 0; i--)
{
int n = rand.Next(i + 1);
Swap(ref cards[i], ref cards[n]);
}
Code taken from Coding Horror. This is also a recommended reading on how people often do this wrong.
Check out this cool Linq way of doing it:
public class Employee
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
Populate a list:
List<Employee> list = new List<Employee>();
list.Add(new Employee { Id = 1, Name = "Davolio Nancy" });
list.Add(new Employee { Id = 2, Name = "Fuller Andrew" });
list.Add(new Employee { Id = 3, Name = "Leverling Janet" });
list.Add(new Employee { Id = 4, Name = "Peacock Margaret" });
list.Add(new Employee { Id = 5, Name = "Buchanan Steven" });
list.Add(new Employee { Id = 6, Name = "Suyama Michael" });
list.Add(new Employee { Id = 7, Name = "King Robert" });
list.Add(new Employee { Id = 8, Name = "Callahan Laura" });
list.Add(new Employee { Id = 9, Name = "Dodsworth Anne" });
Then sort:
list = list.OrderBy(emp => Guid.NewGuid()).ToList();
Credit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With