问题描述
我有以下列表,我想将model
输出到列表中,但要随机进行.我已经看到了一些示例,但是它们似乎真的很混乱.我只是想要一个简单的方法来做到这一点?
Hi I have the following list and I want to output the model
into 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?
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"));
推荐答案
我想您想要的就是这个,这是一种简单的方法;
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假设这是您的属性的名称
//Model is assuming that's the name of your property
注意:具有讽刺意味的是,Random()实际上并不是很随机,但是对于快速简单的解决方案来说是很好的.有更好的算法可以做到这一点,下面是其中一个;
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;
http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
这篇关于随机随机播放列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!