I have a list of objects and I want to reorder them randomly on each request. What is the best way of doing this?
问题:
回答1:
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.
回答2:
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
回答3:
You could use the Fisher-Yates shuffle algorithm which runs in linear-time.
回答4:
Let me direct you to one WRONG way of doing it, and a way I confess I used before, and never saw the error of it until this blog post:
http://www.codinghorror.com/blog/archives/001015.html
回答5:
My favorite solution to shuffling stuff is use an N*log N sort and pass it a sort predicate that returns a random result. It has the nice feature that is can be done with a minimum of new code using building blocks that most languages have handy in even the most striped versions.
回答6:
I would create a new List and filling it with items that are randomly selected and removed from the original List.
回答7:
Try this code here
It uses the IComparer.Compare
It will be a good practice if you do the function using generics