C#Linq-按ASC顺序从VALUE开始

Kli*_*ker 2 c# linq

我有一个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)

Jon*_*eet 5

您当前的代码有两个问题:

  • 根据值是否至少进行排序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)