Random array using LINQ and C#

后端 未结 6 1479
北恋
北恋 2020-12-02 00:10

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

6条回答
  •  星月不相逢
    2020-12-02 00:34

    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 numbers = Enumerable.Range(1, 100).OrderBy(r =>
       {
           timesCalled++;
           return rnd.Next();
       }
    ).ToList();
    
    Assert.AreEqual(timesCalled, 100);
    

提交回复
热议问题