什么是随机重新安排在C#中的项目列表的最佳方法?方法、项目、列表

2023-09-03 10:29:07 作者:惧友

我有一个对象列表,我想随机重新排序的每个请求。什么是这样做的最好方法是什么?

I have a list of objects and I want to reorder them randomly on each request. What is the best way of doing this?

推荐答案

怎么样某种克努特 - 费舍尔-Yates洗牌算法?

for (int i = cards.Length - 1; i > 0; i--)
{
    int n = rand.Next(i + 1);
    Swap(ref cards[i], ref cards[n]);
}

code取自编码恐怖。这也是对人们如何经常做错误的一个建议阅读。

Code taken from Coding Horror. This is also a recommended reading on how people often do this wrong.