Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special case of OrderBy

Tags:

c#

sorting

linq

What does

.OrderBy(x => x == somevalue)

do? It sorts the some value-elements 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
like image 711
kame Avatar asked Apr 02 '18 07:04

kame


People also ask

Why is ORDER BY not allowed in VIEWs?

VIEWs are nothing but just a stored query, they do not contain any data like tables does. When you run a VIEW a table is queries and records are retrieved. And when VIEWs does not contain any data, so there is no sense to provide an order.

Can we apply ORDER BY in two columns?

You can also ORDER BY two or more columns, which creates a nested sort . The default is still ascending, and the column that is listed first in the ORDER BY clause takes precedence. The following query and Figure 3 and the corresponding query results show nested sorts.

What is the use of ORDER BY in SQL?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Can ORDER BY be used without group by?

Key Differences between GROUP BY and ORDER BY The Group By clause is used to group data based on the same value in a specific column. The ORDER BY clause, on the other hand, sorts the result and shows it in ascending or descending order. It is mandatory to use the aggregate function to use the Group By.

How do you write ORDER BY queries?

Syntax. SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause.

How do you use ORDER BY case?

CASE Syntax: CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 WHEN condition3 THEN result3 ELSE result END; ORDER BY: This keyword is used to sort the result-set in ascending or descending order. It sorts the records in ascending order by default.


1 Answers

You are ordering by bool, since x == 2 is a bool value (true if x == 2, false otherwise). In case of bool (bool implements IComparable<bool>)

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

 false < true

that's why

 OrderBy(x => x == 2)

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

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

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

like image 193
Dmitry Bychenko Avatar answered Sep 21 '22 09:09

Dmitry Bychenko