Start learning free

LESSON 22 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V2 in C#: Descending Ordinal Sort with a Lambda

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -r flag baked in. Given a list of lines, return them sorted in descending order by character code (the exact reverse of v1's order, like LC_ALL=C sort -r: lowercase letters come before uppercase ones), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

public string SortLines(List<string> lines)

Example:

Input: lines = ["banana", "apple", "cherry"]

Output: "cherry\nbanana\napple"

When printed:
cherry
banana
apple

Sort with a comparator that compares in reverse, e.g. string.Compare(b, a, StringComparison.Ordinal), then combine with string.Join("\n", ...).

The full solution:
class Solution {
    public string SortLines(List<string> lines) {
        List<string> sortedLines = new List<string>(lines);
        sortedLines.Sort((a, b) => string.Compare(b, a, StringComparison.Ordinal));
        return string.Join("\n", sortedLines);
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Sort V2 in C#, explained

    Problem overview

    This version of SortLines takes a List<string> and returns the lines in descending order by character code, joined with "\n". It is the exact reverse of the previous lesson's order, like LC_ALL=C sort -r, so lowercase letters come before uppercase ones. Duplicates are kept, and an empty list gives "".

    For ["banana", "apple", "cherry"] the result is "cherry\nbanana\napple".

    Approach: swap the arguments of the comparison

    A sort asks a comparison function one question over and over: given a and b, which comes first? The answer is a number. Negative means a first, positive means b first, and zero means they tie.

    string.Compare(a, b, StringComparison.Ordinal) gives that answer for ascending order. To sort descending, ask the same question with the two strings swapped: string.Compare(b, a, StringComparison.Ordinal). Whenever a is bigger, the swapped call returns a negative number, so a goes first.

    Here is one comparison traced. The sort is deciding between a = "cherry" and b = "apple". The lambda evaluates string.Compare("apple", "cherry", StringComparison.Ordinal). a comes before c in character code, so the result is negative, and "cherry" is placed first. For a = "apple" and b = "cherry" the result is positive, so "cherry" is again placed first. Whichever order the sort asks in, the larger string wins.

    The lesson passes this comparison to Sort as a lambda, a small unnamed function written inline.

    Step by step

    1. Copy the input into sortedLines with new List<string>(lines). Sorting happens in place, and the copy keeps the caller's list in its original order.
    2. Sort with a lambda. (a, b) => string.Compare(b, a, StringComparison.Ordinal) takes two lines and compares them the other way round. StringComparison.Ordinal makes the comparison use character codes, as in the previous lesson, instead of culture rules.
    3. Return string.Join("\n", sortedLines).

    The solution in C#

    class Solution {
        public string SortLines(List<string> lines) {
            List<string> sortedLines = new List<string>(lines);
            sortedLines.Sort((a, b) => string.Compare(b, a, StringComparison.Ordinal));
            return string.Join("\n", sortedLines);
        }
    }
    

    With character codes, "apple" is greater than "Zebra", because a (97) is greater than Z (90). That is why lowercase words come first in this order.

    The C# details:

    • Two ways to say "ordinal". Last lesson used the comparer object StringComparer.Ordinal with Sort. Here string.Compare takes the enum value StringComparison.Ordinal. Both mean "compare by character code".
    • The lambda is a Comparison<string>. List<T>.Sort has an overload that accepts such a function, and the compiler infers that a and b are strings.
    • Don't subtract to compare. For numbers, b - a can overflow for large int values and give the wrong sign. For strings the question doesn't arise, since string.Compare does the work.
    • Ties. Equal strings compare as 0, and the order of equal strings is invisible.

    Complexity

    Time: O(n log n) comparisons for n lines, each comparison costing up to the length of the common prefix. Space: O(n) for the copy and the result.

    Edge cases and common mistakes

    • Empty list. The result is "".
    • Empty lines. In descending order they go last: ["apple", "Zebra", "", "apple"] gives "apple\napple\nZebra\n", which ends with a newline because the final line is empty.
    • Sorting ascending, then reversing. That also works, but the swapped comparison does it in one step.
    • Forgetting StringComparison.Ordinal. string.Compare(b, a) alone uses the current culture's rules, so mixed-case input could come out in a different order.
    • Sorting the caller's list. Without the copy, the caller's list would be reordered too.

    Testing

    • ["banana", "apple", "cherry"] gives "cherry\nbanana\napple".
    • ["apple", "Zebra", "", "apple"] gives "apple\napple\nZebra\n".
    • [] gives "".
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free