随机播放列表
Possible Duplicate:
Randomize a List<T> in C#
I have a list which contains many thousands of FilePath's to locations of audio files, and was wondering which would be the most efficient way to "shuffle" a List?
Any help is greatly appreciated :)
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Fisher-Yates Shuffle 或也称为 Knuth shuffle。
Fisher-Yates Shuffle or as it is also known as, Knuth shuffle.
下面是 Fischer-Yates/Knuth shuffle 的一个简单(但有效)的实现:
或者稍有变化:
由于这是一个 O(n) 操作,因此它是对列表进行洗牌的最有效方法。由于列表中的所有项目都必须有机会被移动,因此不可能比 O(n) 更有效地对列表进行洗牌。
我使用此方法和当前接受的答案 (LINQ OrderBy) 对 100 万个项目进行了 1000 次洗牌,进行了一个小型性能测试,这大约快了 15 倍 (!)。
Here is a simple (yet effective) implementation of the Fischer-Yates/Knuth shuffle:
Or a slight variation:
As this is an O(n) operation, it's the most efficient way of shuffling a list. As all items in the list has to have chance to be moved, it's not possible to shuffle a list more efficiently than O(n).
I made a small performance test by shuffling a million items a thousand times each using this method and the currently accepted answer (LINQ OrderBy), and this is about 15 times (!) faster.
myList.OrderBy(Guid.NewGuid())
myList.OrderBy(Guid.NewGuid())
我从 这个问题添加了 Jon Skeet 的解决方案到我的扩展库。我实现的方法既采用外部随机数生成器,又使用默认实现(随机)创建一个随机数生成器。
I added Jon Skeet's solution from this question to my Extensions library. I implemented methods that both take an external random number generator and create one using a default implementation (Random).