C# 随机打乱列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12180038/
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
Randomly shuffle a List
提问by Peter Crouch
Possible Duplicate:
Randomize a List<T> in C#
shuffle (rearrange randomly) a List<string>
Random plot algorithm
可能的重复:
在 C#
shuffle 中随机化一个 List<T> (随机重新排列)一个 List<string>
随机绘图算法
Hi I have the following list and I want to output the modelinto a list but do so randomly. I have seen a few examples but they seem to be really convuluted. I just want a simple way to do this?
嗨,我有以下列表,我想将其输出model到列表中,但随机执行。我看过一些例子,但它们似乎真的很混乱。我只是想要一个简单的方法来做到这一点?
List<Car> garage ----randomise------> List<string> models
List<Car> garage = new List<Car>();
garage.Add(new Car("Citroen", "AX"));
garage.Add(new Car("Peugeot", "205"));
garage.Add(new Car("Volkswagen", "Golf"));
garage.Add(new Car("BMW", "320"));
garage.Add(new Car("Mercedes", "CLK"));
garage.Add(new Car("Audi", "A4"));
garage.Add(new Car("Ford", "Fiesta"));
garage.Add(new Car("Mini", "Cooper"));
采纳答案by saj
I think all you want is this, it's a simple way to do it;
我想你想要的就是这个,这是一个简单的方法;
Random rand = new Random();
var models = garage.OrderBy(c => rand.Next()).Select(c => c.Model).ToList();
//Model is assuming that's the name of your property
//模型假设这是您的财产的名称
Note : Random(), ironically, isn't actually very random but fine for a quick simple solution. There are better algorithms out there to do this, here's one to look at;
注意:具有讽刺意味的是,Random() 实际上并不是很随机,但对于快速简单的解决方案来说很好。有更好的算法可以做到这一点,这里有一个可以看看;
回答by SuperNES
I've seen some messy code for this pre-LINQ, but the LINQ way seems pretty clean.
我已经看到过一些凌乱的 LINQ 之前的代码,但是 LINQ 的方式看起来很干净。
Maybe give this a shot?
也许试一试?
http://www.ookii.org/post/randomizing_a_list_with_linq.aspx
http://www.ookii.org/post/randomizing_a_list_with_linq.aspx
Random rnd = new Random();
var randomizedList = from item in list
orderby rnd.Next()
select item;

