Start learning free

LESSON 375 OF 413 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v4 — Concatenate Multiple Files in C#

Practice

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

    Cat V4 in C#

    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free