定制订单,可以吗?
我有以下收藏:
-3, -2, -1, 0, 1, 2, 3
如何在单个 order by
语句中按以下形式对它们进行排序:
负数首先按其(绝对值)排序) 然后是正数。
-1, -2, -3, 0, 1, 2, 3
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
组合排序,首先按符号排序,然后按绝对值排序:
或:
这在概念上类似于 SQL 语句:
在 LINQ-to-Objects 中,排序只执行一次,而不是两次。
警告:如果 x == int.MinValue,Math.Abs(x) 将失败。如果这个边缘情况很重要,那么你必须单独处理它。
Combination sorting, first by the sign, then by the absolute value:
or:
This is conceptually similar to the SQL statement:
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.
这里的想法是比较非负数的值。将负数与值
int.MinValue - n
进行比较,即-2147483648 - n
,并且由于n
是负数,因此我们计算的负数越大,结果的负面结果越低。当列表本身包含数字
int.MinValue
时,它不起作用,因为它的计算结果为0
,它等于0
本身。正如理查德建议的那样,如果您需要全系列,可以使用long
来制作,但性能会因此受到轻微影响。The idea here is to compare non-negative numbers by the value they have. And compare negative numbers with the value
int.MinValue - n
which is-2147483648 - n
and becausen
is negative, the higher negative number we, the lower negative result the outcome will be.It doesn't work when the list itself contains the number
int.MinValue
because this evaluates to0
which would be equal to0
itself. As Richard propose it could be made withlong
´s if you need the full range but the performance will be slightly impaired by this.尝试类似(VB.Net 示例)
...如果值 <1000
Try something like (VB.Net example)
...if the values are <1000
您可以用 LINQ 来表达它,但如果我两年后阅读代码,我更愿意看到类似的内容:
您将需要实现 IComparer。
You could express it in LINQ, but if I were reading the code two years later, I'd prefer to see something like:
You will need to implement IComparer.