Start learning free

LESSON 4 OF 69 · PROJECTS: COMMAND-LINE TOOLS

cat with Many Files in C#: Flattening a List of Lists

Practice Read the full explanation

The real cat command can take many files as arguments and prints them one after another. Build that behavior. Given a list of "files" where each file is itself a list of lines, flatten all lines in order and join them with newlines.

A file can be empty (it adds no lines), and the list can hold no files at all; the result is then an empty string.

Function signature:

public string ConcatCat(List<List<string>> allLines)

Example:

Input: allLines = [["hello", "world"], ["foo", "bar", "baz"]]

Output: "hello\nworld\nfoo\nbar\nbaz"

When printed:
hello
world
foo
bar
baz

Build a flat List<string> with a nested loop, preserving order. Then return string.Join("\n", flat).

List<string> flat = new List<string>();
foreach (List<string> fileLines in allLines) {
    foreach (string line in fileLines) {
        flat.Add(line);
    }
}
return string.Join("\n", flat);


The full solution:
class Solution {
    public string ConcatCat(List<List<string>> allLines) {
        List<string> flat = new List<string>();
        foreach (List<string> fileLines in allLines) {
            foreach (string line in fileLines) {
                flat.Add(line);
            }
        }
        return string.Join("\n", flat);
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Cat V4 in C#, explained

    Problem overview

    The real cat command accepts several files and prints them one after another. This version models that. The method ConcatCat receives a List<List<string>>: each inner list is one "file", made of lines. It returns all the lines, in order, joined by newlines.

    For [["hello", "world"], ["foo", "bar", "baz"]] the result is "hello\nworld\nfoo\nbar\nbaz", which prints as five lines. A file can be empty and adds no lines. If there are no files at all, the result is an empty string.

    Approach

    Joining a list of strings was already solved in the first version of the tool, with string.Join. The only new problem here is that the lines come in several lists. So the work splits in two steps: first flatten the nested lists into one list of lines, then join that list.

    Flattening needs two loops, one inside the other. The outer loop visits the files in order. The inner loop visits the lines of the current file in order. Adding each line to a new list flat keeps the original order: all of file 1, then all of file 2, and so on.

    A separator-based join is also the answer to the "between, not after" rule. Joining the flat list puts a newline between neighbouring lines and none after the last. It doesn't matter which file a line came from. The last line of one file and the first line of the next are simply neighbours. Building the joined string for every file separately and gluing the pieces would need extra care at the file boundaries.

    Step by step

    1. Create flat: List<string> flat = new List<string>();. It will hold every line of every file, with no lists inside it.
    2. Loop over the files with foreach (List<string> fileLines in allLines). Each element of allLines is itself a list of lines.
    3. Loop over the lines of this file with foreach (string line in fileLines), inside the first loop.
    4. Add the line: flat.Add(line). An empty file never enters the inner loop, so it adds nothing.
    5. Return string.Join("\n", flat) after both loops.

    The solution in C#

    class Solution {
        public string ConcatCat(List<List<string>> allLines) {
            List<string> flat = new List<string>();
            foreach (List<string> fileLines in allLines) {
                foreach (string line in fileLines) {
                    flat.Add(line);
                }
            }
            return string.Join("\n", flat);
        }
    }
    

    C# details worth knowing:

    • A list of lists is a type of its own. List<List<string>> is a list whose elements are List<string>. Each inner list can have a different length, including zero. Note the two closing angle brackets.
    • foreach needs no index. Here you only need each item in order, so foreach is shorter and cannot go out of range.
    • Loop variable names say what they hold. fileLines is a whole file, line is one string. Mixing the two up is a type error the compiler catches.
    • Without loops. With using System.Linq;, allLines.SelectMany(f => f) flattens a list of lists, and string.Join("\n", allLines.SelectMany(f => f)) returns the same result as the solution for [["a", "b"], ["c"]], "a\nb\nc". The explicit loops need no extra using and show what happens.
    • string.Join accepts a list directly, so there is no need to convert flat to an array.

    Complexity

    Time: O(total length). Each line is visited once while flattening, and string.Join copies each character once. Adding to a List takes amortised constant time.

    Space: O(total length). flat holds a reference to every line (the line strings themselves are not copied), and the joined result is a new string with all the text.

    Edge cases and common mistakes

    • Empty files. [["a"], [], ["b"]] gives "a\nb". The empty file contributes no line and no extra newline.
    • No files. [] gives "", and so does [[], []].
    • Files with only a blank line. A blank line is still a line. [[""], [""]] gives "\n": two empty lines with a newline between them.
    • A single file. [["x"]] gives "x", with no newline.
    • A newline between files by hand. Appending "\n" after each file leaves a trailing newline at the end, and an empty file would still add a newline of its own. Flattening first avoids both.
    • Changing the order. The files and their lines must stay in the order given. Don't sort.
    • A null file. If one of the inner lists is null, the inner foreach throws a NullReferenceException. The lesson passes real lists, possibly empty ones.

    Testing

    • [["hello", "world"], ["foo", "bar", "baz"]] gives "hello\nworld\nfoo\nbar\nbaz".
    • [["a"], [], ["b"]] gives "a\nb".
    • [] gives "".
    • [[], []] gives "".
    • [[""], [""]] gives "\n".
    • [["x"]] gives "x".
    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