C# 随机列表<T>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2301015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shuffle List<T>
提问by
Possible Duplicate:
Randomize a List<T> in C#
可能的重复:
在 C# 中随机化一个 List<T>
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?
我有一个列表,其中包含数千个指向音频文件位置的 FilePath,并且想知道哪种方法是“随机播放”列表的最有效方法?
Any help is greatly appreciated :)
任何帮助是极大的赞赏 :)
Thank you
谢谢
采纳答案by
Fisher-Yates Shuffleor as it is also known as, Knuth shuffle.
Fisher-Yates Shuffle或也称为 Knuth shuffle。
回答by Esteban Araya
myList.OrderBy(Guid.NewGuid())
myList.OrderBy(Guid.NewGuid())
回答by Guffa
Here is a simple (yet effective) implementation of the Fischer-Yates/Knuth shuffle:
这是 Fischer-Yates/Knuth shuffle 的一个简单(但有效)的实现:
Random rnd = new Random();
for (int i = files.Length; i > 1; i--) {
int pos = rnd.Next(i);
var x = files[i - 1];
files[i - 1] = files[pos];
files[pos] = x;
}
Or a slight variation:
或略有变化:
Random rnd = new Random();
for (int i = 1; i < files.Length; i++) {
int pos = rnd.Next(i + 1);
var x = files[i];
files[i] = files[pos];
files[pos] = x;
}
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).
由于这是一个 O(n) 操作,因此它是对列表进行混洗的最有效方法。由于列表中的所有项目都必须有机会被移动,因此不可能比 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.
我通过使用这种方法和当前接受的答案 (LINQ OrderBy) 将 100 万个项目混洗一千次,进行了一个小型性能测试,这大约快了 15 倍 (!)。
回答by tvanfosson
I added Jon Skeet's solution from this questionto my Extensions library. I implemented methods that both take an external random number generator and create one using a default implementation (Random).
我将这个问题中的Jon Skeet 解决方案添加到我的扩展库中。我实现的方法既采用外部随机数生成器,又使用默认实现(随机)创建一个。