Randomly shuffle a List [duplicate]

2019-06-19 18:26发布

Possible Duplicate:
Randomize a List<T> in C#
shuffle (rearrange randomly) a List<string>
Random plot algorithm

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"));

2条回答
Viruses.
2楼-- · 2019-06-19 19:00

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;

http://en.wikipedia.org/wiki/Fisher-Yates_shuffle

查看更多
smile是对你的礼貌
3楼-- · 2019-06-19 19:10

I've seen some messy code for this pre-LINQ, but the LINQ way seems pretty clean.

Maybe give this a shot?

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;
查看更多
登录 后发表回答