spock
11/7/2018 - 2:28 PM

lock ConsoleTablePrinter

A hacky solution allowing to append rows to an existing table.

Requires: https://github.com/khalidabuhakmeh/ConsoleTables

public class ConsoleTablePrinter<T>
{
    private bool HeaderIsPrinted = false;

    public ConsoleTablePrinter()
    {
    }

    public ConsoleTablePrinter(T row)
    {
        Print(row);
    }

    public ConsoleTablePrinter(IEnumerable<T> rows)
    {
        Print(rows);
    }

    public void Print(T row)
    {
        Print(new List<T> { row });
    }

    public void Print(IEnumerable<T> rows)
    {
        var tableString = ConsoleTable.From<T>(rows).ToMinimalString();

        if (HeaderIsPrinted)
        {
            // HACK: Remove header from subsequent lines
            // No other console table library found which allowed the native
            // suppression of header rendering.
            tableString = tableString.RemoveFirstLines(2);
            Console.CursorTop--;  // move cursor one line up
        }
        else
        {
            HeaderIsPrinted = true;
        }

        Console.WriteLine(tableString);
    }
}

public static class StringExtensions
{
    public static string RemoveFirstLines(this string text, int linesCount)
    {
        var lines = Regex.Split(text, "\r\n|\r|\n").Skip(linesCount);
        return String.Join(Environment.NewLine, lines.ToArray());
    }
}