Shuffle the list randomly

Possible duplicate:
Randomize <T> list in C #
shuffle (random random selection) List <string>
Random plotting algorithm

Hi I have the following list and I want to list model in a list, but do it randomly. I saw a few examples, but they seem really confusing. I just want an easy 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")); 
+6
source share
2 answers

I think all you want is an easy way to do this;

 Random rand = new Random(); var models = garage.OrderBy(c => rand.Next()).Select(c => c.Model).ToList(); 

// The model assumes your property name

Note. Random (), ironically, is actually not very random, but accurate for a quick, easy solution. There are better algorithms for this; here is one to watch;

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

+10
source

I saw some dirty code for this pre-LINQ, but the LINQ method seems pretty clean.

Maybe this is 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; 
-1
source

Source: https://habr.com/ru/post/924085/


All Articles