Random array using LINQ and C#

Solution 1:

The Developer Fusion VB.Net to C# converter says that the equivalent C# code is:

System.Random rnd = new System.Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());

For future reference, they also have a C# to VB.Net converter. There are several other tools available for this as well.

Solution 2:

I initially thought this would be a bad idea since the sort algorithm will need to do multiple comparisons for the numbers, and it will get a different sorting key for the same number each time it calls the lambda for that number. However, it looks like it only calls it once for each element in the list, and stores that value for later use. This code demonstrates this:

int timesCalled = 0;
Random rnd = new Random();

List<int> numbers = Enumerable.Range(1, 100).OrderBy(r =>
   {
       timesCalled++;
       return rnd.Next();
   }
).ToList();

Assert.AreEqual(timesCalled, 100);

Solution 3:

Random rnd = new Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());

Solution 4:

What about something far more easy...

Enumerable.Range(1, 100).OrderBy(c=> Guid.NewGuid().ToString())

Solution 5:

Best I can do off the top of my head without access to Visual Studio (crosses fingers):

System.Random rnd = New System.Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(rnd => rnd.Next);