[ACCEPTED]-Random array using LINQ and C#-enumerable

Accepted answer
Score: 20

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 2 future reference, they also have a C# to VB.Net converter. There 1 are several other tools available for this as well.

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

0

Score: 5

I initially thought this would be a bad 8 idea since the sort algorithm will need 7 to do multiple comparisons for the numbers, and 6 it will get a different sorting key for 5 the same number each time it calls the lambda 4 for that number. However, it looks like 3 it only calls it once for each element in 2 the list, and stores that value for later 1 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);
Score: 4

What about something far more easy...

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

0

Score: 1

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

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

Using the C5 Generic Collection Library, you could just use the builtin 1 Shuffle() method:

IList<int> numbers = new ArrayList<int>(Enumerable.Range(1,100));
numbers.Shuffle();

More Related questions