Skip to content

Instantly share code, notes, and snippets.

@rquackenbush
Last active January 5, 2023 18:15
Show Gist options
  • Save rquackenbush/f8b3d1db7728d387c3061b1866bacf0c to your computer and use it in GitHub Desktop.
Save rquackenbush/f8b3d1db7728d387c3061b1866bacf0c to your computer and use it in GitHub Desktop.
Text columnizer
using System.Text;
namespace ConsoleApp1
{
public static class Columnizer
{
public static IEnumerable<string> Columnize(IList<string> headers, IList<string[]> rows, string separator = " ")
{
// Start with the lengths of the column headers
int[] columnWidths = headers
.Select(h => (h ?? "").Length)
.ToArray();
//First pass, get the lengths
foreach (var row in rows)
{
if (columnWidths.Length != row.Length)
throw new InvalidOperationException();
for (int x = 0; x < row.Length; x++)
{
columnWidths[x] = Math.Max(columnWidths[x], (row[x] ?? "").Length);
}
}
var rowTemp = new string[columnWidths.Length];
//Format the column names
for(int h = 0; h < columnWidths.Length; h++)
{
rowTemp[h] = (headers[h] ?? "").PadRight(columnWidths[h], ' ');
}
yield return string.Join(separator, rowTemp);
//Separator row
for (int h = 0; h < columnWidths.Length; h++)
{
rowTemp[h] = ("").PadRight(columnWidths[h], '-');
}
yield return string.Join(separator, rowTemp);
//Format the body
foreach (var row in rows)
{
for (int x = 0; x < row.Length; x++)
{
rowTemp[x] = (row[x] ?? "").PadRight(columnWidths[x], ' ');
}
yield return string.Join(separator, rowTemp); ;
}
}
}
}
var rows = new List<string[]>
{
new string[] { "Dean Koontz", "Intensity" },
new string[] { "Stephen King", "It" },
new string[] { "James Clear", "Atomic Habits" }
};
var headers = new string[]
{
"Author",
"Book"
};
var lines = Columnizer.Columnize(headers, rows);
foreach(var line in lines)
{
Console.WriteLine(line);
}
Author Book
------------ -------------
Dean Koontz Intensity
Stephen King It
James Clear Atomic Habits
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment