using System.Collections.Generic;
public class TablePrinter
private readonly string[] titles;
private readonly List<int> lengths;
private readonly List<string[]> rows = new List<string[]>();
public TablePrinter(params string[] titles)
lengths = titles.Select(t => t.Length).ToList();
public void AddRow(params object[] row)
if (row.Length != titles.Length)
throw new System.Exception("Added row length [{row.Length}] is not equal to title row length [{titles.Length}]");
rows.Add(row.Select(o => o.ToString()).ToArray());
for (int i = 0; i < titles.Length; i++)
if (rows.Last()[i].Length > lengths[i])
lengths[i] = rows.Last()[i].Length;
lengths.ForEach(l => System.Console.Write("+-" + new string('-', l) + '-'));
System.Console.WriteLine("+");
for (int i = 0; i < titles.Length; i++)
line += "| " + titles[i].PadRight(lengths[i]) + ' ';
System.Console.WriteLine(line + "|");
lengths.ForEach(l => System.Console.Write("+-" + new string('-', l) + '-'));
System.Console.WriteLine("+");
foreach (var row in rows)
for (int i = 0; i < row.Length; i++)
if (int.TryParse(row[i], out n))
line += "| " + row[i].PadLeft(lengths[i]) + ' ';
line += "| " + row[i].PadRight(lengths[i]) + ' ';
System.Console.WriteLine(line + "|");
lengths.ForEach(l => System.Console.Write("+-" + new string('-', l) + '-'));
System.Console.WriteLine("+");
public static void Main()
var t = new TablePrinter("id", "Column A", "Column B");
t.AddRow(1, "Val A1", "Val B1");
t.AddRow(2, "Val A2", "Val B2");
t.AddRow(100, "Val A100", "Val B100");