Linq OrderBy logic

c#, linq

Solution

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.

Problem

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?

Original source