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.
OrderByguarantees that. - Character-code order. Passing
StringComparer.Ordinalas a second argument tellsOrderByto 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
- Sort and collect in one statement.
lines.OrderBy(...)followed byToList()produces the newList<string>namedsortedLines. The original list is not touched, so there's no separate copy. - 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, hencefield - 1. - Pass
StringComparer.Ordinalas the second argument ofOrderBy. - 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:
Splitkeeps 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
OrderByneeds a comparer for strings. Without the second argument it would use the default comparer, which follows culture rules. - The overload.
OrderByaccepts a key selector and then anIComparerfor the keys.StringComparer.Ordinalis 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.
fieldis trusted. If a line had fewer fields, the index would be out of range and throw anIndexOutOfRangeException. 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 = 2and["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, andxstays ahead ofwbecause 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", sinceBhas a smaller code thana. - 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"".
