如何在c#中对数字进行排序?

use*_*550 2 c# sorting

对于与前者的差异小于3的每个元素,按降序排序

numbers = {1,2,3,4,5,6,13,18,25,30,31,32,33}

desired = {6,5,4,3,2,1,13,18,25,33,32,31,30}
Run Code Online (Sandbox Code Playgroud)

例如在数字列表中,因为6和5之间的差异小于3,所以它们以降序排序

dtb*_*dtb 6

您可以使用LINQ:

var numbers = new int[] { 1, 2, 3, 4, 5, 6, 13, 18, 25, 30, 31, 32, 33 };

var result = numbers.GroupAdjacent((x, y) => y - x < 3)
                    .SelectMany(g => g.OrderByDescending(x => x))
                    .ToArray();

// result == { 6, 5, 4, 3, 2, 1, 13, 18, 25, 33, 32, 31, 30 }
Run Code Online (Sandbox Code Playgroud)

static IEnumerable<IEnumerable<T>> GroupAdjacent<T>(
    this IEnumerable<T> source, Func<T, T, bool> adjacent)
{
    var g = new List<T>();
    foreach (var x in source)
    {
        if (g.Count != 0 && !adjacent(g.Last(), x))
        {
            yield return g;
            g = new List<T>();
        }
        g.Add(x);
    }
    yield return g;
}
Run Code Online (Sandbox Code Playgroud)