Start learning free

LESSON 24 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V4 in C#: Stable Sort by a Comma-Separated Field

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -k flag baked in. Each input line is comma-separated and is guaranteed to have at least field fields (a field may be empty, as in "a,,c"). Given a 1-indexed field number, sort the lines stably by the value at that field, compared as strings by character code, and return the original lines joined by newlines (\n). Lines whose fields are equal keep their original relative order. This matches the real command sort -t, -k N,N -s in the C locale. If the list is empty, return the empty string.

Function signature:

public string SortLines(List<string> lines, int field)

Example:

Input: field = 2, lines = ["alice,30", "bob,25", "carol,40"]

Output: "bob,25\nalice,30\ncarol,40"

When printed:
bob,25
alice,30
carol,40

Use LINQ's OrderBy, which is a stable sort (unlike List.Sort). Key on each line's field - 1 element after splitting on ",", and pass StringComparer.Ordinal for plain string comparison.

The full solution:
class Solution {
    public string SortLines(List<string> lines, int field) {
        List<string> sortedLines = lines.OrderBy(l => l.Split(",")[field - 1], StringComparer.Ordinal).ToList();
        return string.Join("\n", sortedLines);
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Sort V4 in C#, explained

    Problem overview

    The method SortLines(List<string> lines, int field) mimics sort -t, -k N,N -s in the C locale. Each line is comma-separated and has at least field fields. The field number counts from 1. The method sorts the lines stably by the text of that field, compared by character code, and returns the original lines joined with "\n". A field may be empty, as in "a,,c". An empty list gives "".

    For field = 2 and ["alice,30", "bob,25", "carol,40"], the second fields are 30, 25 and 40, so the result is "bob,25\nalice,30\ncarol,40".

    Approach: sort the whole line by one piece of it

    As in the numeric lesson, the output keeps the original strings, and only the sort key differs from the string itself. The key here is the field: split the line at commas and take one piece. Two requirements follow:

    • Stability. Lines with equal fields must stay in their input order. OrderBy guarantees that.
    • Character-code order. Passing StringComparer.Ordinal as a second argument tells OrderBy to compare the keys by code, not by culture rules.

    The key compares as text, so a field holding numbers sorts as text too: with field = 2, ["a,10", "b,9", "c,100"] gives "a,10\nc,100\nb,9".

    Step by step

    1. Sort and collect in one statement. lines.OrderBy(...) followed by ToList() produces the new List<string> named sortedLines. The original list is not touched, so there's no separate copy.
    2. Write the key lambda. l => l.Split(",")[field - 1] splits the line at commas and picks one piece. Fields count from 1 and array positions from 0, so field 2 is position 1, hence field - 1.
    3. Pass StringComparer.Ordinal as the second argument of OrderBy.
    4. Return string.Join("\n", sortedLines).

    The solution in C#

    class Solution {
        public string SortLines(List<string> lines, int field) {
            List<string> sortedLines = lines.OrderBy(l => l.Split(",")[field - 1], StringComparer.Ordinal).ToList();
            return string.Join("\n", sortedLines);
        }
    }
    

    The C# details:

    • Split keeps empty fields. "a,,c".Split(",") gives three pieces: "a", "" and "c". The empty piece is a valid key, and in character-code order it comes before any non-empty text.
    • The lambda returns a string, so OrderBy needs a comparer for strings. Without the second argument it would use the default comparer, which follows culture rules.
    • The overload. OrderBy accepts a key selector and then an IComparer for the keys. StringComparer.Ordinal is such a comparer.
    • The key is the field only. Unlike a plain sort of the whole lines, the rest of the line plays no part, which is why equal fields keep their input order.
    • field is trusted. If a line had fewer fields, the index would be out of range and throw an IndexOutOfRangeException. The lesson guarantees enough fields.

    Complexity

    Time: O(n log n) comparisons for n lines, plus the cost of splitting each line once and comparing keys. Space: O(n) for the key pieces, the sorted list and the joined string.

    Edge cases and common mistakes

    • Empty list. The result is "".
    • Ties keep input order. For field = 2 and ["x,b,1", "y,,2", "z,a,3", "w,b,4"] the result is "y,,2\nz,a,3\nx,b,1\nw,b,4": the empty field is first, and x stays ahead of w because it came first.
    • Off by one. Using Split(",")[field] sorts by the wrong column and can throw on the last field.
    • Case. With field = 1, ["b,2", "B,1", "a,3"] gives "B,1\na,3\nb,2", since B has a smaller code than a.
    • Numbers sort as text. A field of numbers needs numeric parsing for numeric order, as in the previous lesson.
    • Sorting the fields instead of the lines. The output has to contain the whole original lines.

    Testing

    • field = 2, ["alice,30", "bob,25", "carol,40"] gives "bob,25\nalice,30\ncarol,40".
    • field = 1, ["b,2", "B,1", "a,3"] gives "B,1\na,3\nb,2".
    • field = 2, ["a,10", "b,9", "c,100"] gives "a,10\nc,100\nb,9".
    • field = 1, [] 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