0

I'm wondering, what is a proper way to mix List<string> list = new List<string>(); content inside the list randomly, without using of another list for random rewriting.

For example, if I got value by index this way:

list[0];
list[1];
list[2];
list[3];

and order output is:

line1
line2
line3
line4

after desired mixing, how is possible to get it under the same indexes, but over the randomly mixed values:

list[0];
list[1];
list[2];
list[3];

to get random order inside the list:

line2
line4
line1
line3
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
nikorio
  • 671
  • 4
  • 16
  • 28

1 Answers1

1

Try this:

// Create an randomizer object
Random r = new Random();

// Create a list of strings
List<string> list = new List<string>() { "line1", "line2", "line3", "line4" };

// Sort list randomly
list = list.OrderBy(x=>r.Next()).ToList();
Ivan Kishchenko
  • 795
  • 4
  • 15
  • Is it guaranteed that the lambda in OrderBy is only called once per item? If not then two different calls on the same item will return different values. The order would still be random but it might cause unexpected behaviour. (Note: the fact that the current implementation calls the lambda only once per item does not mean future implementations will do the same) – P. Kouvarakis Mar 24 '17 at 18:23
  • This is traditionally bad implementation of shuffle. please don't use it. Note that question explicitly asked for "proper way to mix" and not "a way to shuffle list" which is demonstrated in this answer. – Alexei Levenkov Mar 24 '17 at 18:25
  • Its also not doing the shuffling in- place, which was if I am not mistaken a requirement in the question. – BitTickler Mar 24 '17 at 18:26
  • The task was to sort the order of the list in a random sequence. This example does it perfectly and quickly. – Ivan Kishchenko Mar 24 '17 at 18:26