我有一个int数组,我想从某个值开始按升序对这些值进行排序,我们将其称为startValue。但是,我想保留所有值,并且大于该值的值startValue将出现在列表中的最大值之后。
用一个例子可能更容易解释...
int[] values = new int[] { 1, 2, 4, 6, 9 };
int startValue = 4;
int[] orderedValues = { 4, 6, 9, 1, 2 }; // desired result
Run Code Online (Sandbox Code Playgroud)
我该如何实现?我认为这样可以解决问题,但是新orderedValues的顺序与原始值相同。
int[] orderedValues = values.OrderBy( v => v >= startValue ).ToArray();
Run Code Online (Sandbox Code Playgroud)
您当前的代码有两个问题:
startValue,而不是根据值本身进行排序(“升序”部分)false是在之前订购的true,因此您需要逆转条件这是一个很好的示例:
using System;
using System.Linq;
class Test
{
static void Main()
{
int[] values = new int[] { 1, 2, 4, 6, 9 };
int startValue = 4;
int[] orderedValues = values
.OrderBy(v => v < startValue) // Note reversed comparison
.ThenBy(v => v) // Order by value within each segment
.ToArray();
Console.WriteLine(string.Join(", ", orderedValues));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
144 次 |
| 最近记录: |