Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom order by, is it possible?

Tags:

c#

linq

I have the following collection:

-3, -2, -1, 0, 1, 2, 3

How can I in a single order by statement sort them in the following form:

The negative numbers are sorted first by their (absolute value) then the positive numbers.

-1, -2, -3, 0, 1, 2, 3

like image 887
Homam Avatar asked Jan 26 '26 22:01

Homam


1 Answers

Combination sorting, first by the sign, then by the absolute value:

list.OrderBy(x => Math.Sign(x)).ThenBy(x => Math.Abs(x));

or:

from x in list
orderby Math.Sign(x), Math.Abs(x)
select x;

This is conceptually similar to the SQL statement:

SELECT x
FROM list
ORDER BY SIGN(x), ABS(x)

In LINQ-to-Objects, the sort is performed only once, not twice.

WARNING: Math.Abs(x) will fail if x == int.MinValue. If this marginal case is important, then you have to handle it separately.

like image 148
Stephen Chung Avatar answered Jan 29 '26 10:01

Stephen Chung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!