Skip to content

Instantly share code, notes, and snippets.

@flytzen
Last active September 7, 2021 12:40
Show Gist options
  • Save flytzen/a33b1be7423b528b433d946bde29c036 to your computer and use it in GitHub Desktop.
Save flytzen/a33b1be7423b528b433d946bde29c036 to your computer and use it in GitHub Desktop.
Write markdown table from an array
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace ArrayPlay
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting");
string[][] array = new string[][]
{
new string[] {"Name", "Pay", "Job"},
new string[] {"A","B","C"},
new string[] {"safjASDFKJASDKFJSDKFJDKSFKDFJ!", "ASD", "2" }
};
AddTable(array);
}
private static void AddTable(string[][] data)
{
var sb = new StringBuilder();
// This is using a jagged array even though a 2-dimensional array would be more logical, mostly because
// 2d arrays are hard to build for callers.
int rowCount = data.Length;
int colCount = data[0].Length;
// Check all rows are same length
if (data.Any(r => r.Length != colCount))
{
throw new ArgumentException("Not all rows have the same number of columns", nameof(data));
}
// Work out column widths
Span<ushort> colDimensions = stackalloc ushort[colCount];
for (int column = 0; column < colCount; column++)
{
colDimensions[column] = (ushort)data.Select(r => r[column].Length).Max();
}
for (int rowNum = 0; rowNum < rowCount; rowNum++)
{
var row = data[rowNum];
sb.Append('|');
for (int column = 0; column < colCount; column++)
{
sb.Append(row[column].PadRight(colDimensions[column]));
sb.Append('|');
}
sb.AppendLine();
if (rowNum == 0)
{
sb.Append('|');
for (int column = 0; column < colCount; column++)
{
sb.Append(new string('-', colDimensions[column]));
sb.Append('|');
}
sb.AppendLine();
}
}
Console.Write(sb.ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment