Start learning free

LESSON 377 OF 413 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v2 — First n Lines in C#

Practice

Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ lines.Count. If n is 0 the result is the empty string.

Function signature:

public string Head(List<string> lines, int n)

Example:

Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3

Output: "alpha\nbeta\ngamma"

When printed:
alpha
beta
gamma

Use lines.GetRange(0, n) for the first n elements, then string.Join("\n", ...). Since the problem guarantees n ≤ lines.Count, no Min needed.

Combine the two calls into one:
return string.Join("\n", lines.GetRange(0, n));


The full solution:
class Solution {
    public string Head(List<string> lines, int n) {
        return string.Join("\n", lines.GetRange(0, n));
    }
}

STEP 1 OF 1
    Ctrl + Enter to check

    Head V2 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