Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq OrderBy logic

Tags:

c#

linq

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?

like image 291
Alex Avatar asked Dec 15 '22 15:12

Alex


1 Answers

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.

like image 81
usr Avatar answered Jan 03 '23 06:01

usr