How to shuffle list of strings in C #?

4

I have a console application, in which the list exists:

List <string> ListaFrases = new List<string>(); 

This list is built through the user inputs on the console. How to display your strings, but so that their positions are "shuffled", that is, displayed in random order?

    
asked by anonymous 03.10.2017 / 22:18

1 answer

7

Use the Random class. It does a simple but effective randomization.

Example:

List <string> ListaFrases = new List<string>(); 
var rnd = new Random(); // Randomizador

// Cria uma nova lista com as frases embaralhadas.
var ListaFrasesRandom = ListaFrases.OrderBy(x => rnd.Next()).ToList();

Or if you just want to display the scrambled list instead of creating a new list.

ListaFrases.OrderBy(x => rnd.Next()).ToList().ForEach(Console.WriteLine);

See working in .NET Fiddle

    
03.10.2017 / 22:24