I'm trying to understand the custom sorting logic of the following LINQ query:
var random = new Random();
var cnt = Enumerable.Range(0, 10).OrderBy(i => random.NextDouble()).ToList();
What is the inner logic of such comparision and how does i compares to random.NextDouble() inside making the result list always different?
It is equivalent to:
var cnt =
Enumerable.Range(0, 10)
.Select(i => new { i, rand = random.NextDouble() }) //"weave" the random temporary
.OrderBy(x => x.rand) //sort
.Select(x => x.i) //remove it
.ToList();
The random value logically becomes part of the list.
As an implementation detail (as of .NET 2.0 to 4.5), OrderBy
materializes the sort key so that it is evaluated exactly one for each element. It does this for performance and (in your case) for correctness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With