我有一个对象列表,我想在每个请求上随机重新排序.这样做的最佳方式是什么?
某种Knuth-Fisher-Yates shuffle算法怎么样?
for (int i = cards.Length - 1; i > 0; i--) { int n = rand.Next(i + 1); Swap(ref cards[i], ref cards[n]); }
代码取自Coding Horror.这也是关于人们经常如何做错的推荐读物.
看看这个酷炫的Linq做法:
public class Employee { public int Id { get; set; } public string Name { get; set; } }
填充列表:
Listlist = new List (); 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" });
然后排序:
list = list.OrderBy(emp => Guid.NewGuid()).ToList();
信用