How to shuffle string list in c#?

Asked

Viewed 436 times

4

I have a console application, in which there is a list:

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

This list is built through user inputs in the console. How to display your strings, but in such a way that their position is "shuffled", that is, displayed in random order?

1 answer

7


Use the class Random. It makes 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 shuffled list instead of creating a new list.

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

See working on . NET Fiddle

  • Does this generate draw without repetition? Or can the elements be repeated? For the intention would be to draw without repetition.

  • 1

    Without repetition, the OrderBy walks through the list and changes the order of each item only once, without generating duplicity.

  • How to understand the logic of this excerpt? x => Rnd.Next())

  • 1

    rnd.Next() will provide you with a random number. The x is the entry in your string list. The OrderBy(x => rnd.Next()) is saying that each item (x) will be ordered by a random number rnd.Next(), then, for example, item 1 will receive the number 76 and item 2 the number 31, causing them to be in different orders.

  • Right, but I thought that x => Rnd. Next() would be something like "x will be greater or equal to random. I didn’t quite understand the logic

  • 1

    Ah, this is a complex starting point. This is called Lamda expressions (lambda Expressions). Check out the explanation in this post https://answall.com/questions/2822/o-que-são-lambda-expressions-e-qual-sacada-usá-las

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.