什么是随机重新安排在C#中的项目列表的最佳方法? [英] What is the best way of randomly re-arranging a list of items in c#?

查看:146
本文介绍了什么是随机重新安排在C#中的项目列表的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于什么是随机重新安排在C#中的项目列表的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆