Special occasion OrderBy

What is he doing

.OrderBy(x => x == somevalue) 

make? It sorts some element values ​​to the end. But why?

Code example:

 var arr = new int[] { 1, 2, 3 }; var arr2 = arr.OrderBy(x => x == 2).ToArray(); // arr2 --> 1, 3, 2 
+5
source share
1 answer

You order bool , since x == 2 is the value of bool ( true if x == 2 , false otherwise). In the case of bool ( bool implements IComparable<bool> )

https://msdn.microsoft.com/en-us/library/kf07t5s5(v=vs.110).aspx

  false < true 

why

  OrderBy(x => x == 2) 

means "first values ​​that are not equal to 2 , and then 2 s".

  {1, 2, 3} -> {1, 3, 2} 

Edit: Finally, OrderBy is stable sorting, so the initial order 1, ..., 3 ( 1 to 3 ) has been preserved (if you sort the array with an unstable sorting algorithm, say quicksort, you can have {3, 1, 2} as a result)

+17
source

Source: https://habr.com/ru/post/1276210/


All Articles