Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random array using LINQ and C#

I was reading an article on MSDN Magazine about using the Enumerable class in LINQ to generate a random array. The article uses VB.NET and I'm not immediately sure what the equivalent is in C#:

Dim rnd As New System.Random()
Dim numbers = Enumerable.Range(1, 100). _
    OrderBy(Function() rnd.Next)
like image 798
Ryan Avatar asked Oct 31 '08 20:10

Ryan


3 Answers

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.

like image 162
HanClinto Avatar answered Oct 20 '22 09:10

HanClinto


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);
like image 40
Daniel Plaisted Avatar answered Oct 20 '22 09:10

Daniel Plaisted


Random rnd = new Random();
IEnumerable<int> numbers = Enumerable.Range(1, 100).OrderBy(r => rnd.Next());
like image 5
James Curran Avatar answered Oct 20 '22 09:10

James Curran