Last active
January 5, 2023 18:15
-
-
Save rquackenbush/f8b3d1db7728d387c3061b1866bacf0c to your computer and use it in GitHub Desktop.
Text columnizer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); ; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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