[Solved] C# sorts range of elements in descending order


Using System.Linq, you can Take the first two items, then Concat that with the rest of the list after calling Reverse:

var items = new[] {1, 2, 3, 4, 5};
var sorted = items.Take(2).Concat(items.Skip(2).Reverse());

Update: You can take this logic and create a more generic implementation, such as:

private static int[] SortRangeReverse(int[] input, int startRange, int endRange)
{
    // Argument validation - decide what you want to do if the args aren't what you expect
    if (input == null || input.Length < 2) return input;
    if (endRange <= startRange) return input;
    if (startRange < 0) startRange = 0;

    // The actual "meat" of the original answer in a more generic form:
    return
        input.Take(startRange)
            .Concat(input.Skip(startRange).Take(endRange + 1 - startRange).Reverse()
            .Concat(input.Skip(endRange + 1)))
            .ToArray();
}

9

solved C# sorts range of elements in descending order