0

Consider the following code:

string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
IEnumerable<string> randoms = Enumerable.Range(1, 10)
                              .Select(i => 
                              new string(alphabet
                                         .OrderBy(c => new Random().Next())
                                         .ToArray()));

As you can see I am ordering by new Random().Next() which should be a different number in each evaluation, right?

However this is the result I am getting:

ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ

As you can see none of the characters got shuffled.

What is happening here?

Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • 2
    http://stackoverflow.com/a/768001/130387 – Tommy Oct 31 '15 at 02:55
  • Maybe put the toarray first. Alphabet is a string, not an array. – toddmo Oct 31 '15 at 03:00
  • @toddmo Actually, `string` implements `IEnumerable` so I can use LINQ on it – Matias Cicero Oct 31 '15 at 03:11
  • Run your current new string expression in the immediate window twice and see if that works. Might give a clue. – toddmo Oct 31 '15 at 03:15
  • 1
    @toddmo The duplicate linked explains the problem very well, its nothing to do with the array or working with the debugger, it has to do with the resolution of the clock and a tight loop seeding the random number generator with the same value, therefore getting the same `.Next` each time its run. – Ron Beyer Oct 31 '15 at 03:29

0 Answers0