Skip to content

Instantly share code, notes, and snippets.

@jpierson
Last active January 25, 2017 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpierson/43b3a77decac98e9fc7289827ed6580e to your computer and use it in GitHub Desktop.
Save jpierson/43b3a77decac98e9fc7289827ed6580e to your computer and use it in GitHub Desktop.
Linq style extension method for producing a table in markdown format from IEnumerable<T> source.
public static class LinqMarkdownTableExtensions
{
public static string ToMarkdownTable<T>(this IEnumerable<T> source)
{
var properties = typeof(T).GetProperties();
var maxColumnValues = source
.Select(x => properties.Select(p => p.GetValue(x)?.ToString()?.Length ?? 0))
.Union(new[] { properties.Select(p => p.Name.Length) }) // Include header in column sizes
.Aggregate(
new int[properties.Length].AsEnumerable(),
(accumulate, x) => accumulate.Zip(x, Math.Max))
.ToArray();
var columnNames = properties.Select(p => p.Name);
var headerLine = "| " + string.Join(" | ", columnNames.Select((n, i) => n.PadRight(maxColumnValues[i]))) + " |";
var headerDataDividerLine = "| " + string.Join(" | ", properties.Select((n, i) => new string('-', maxColumnValues[i]))) + " |";
var lines = new[]
{
headerLine,
headerDataDividerLine,
}.Union(
source
.Select(s =>
"| " + string.Join(" | ", properties.Select((n, i) => (n.GetValue(s)?.ToString() ?? "").PadRight(maxColumnValues[i]))) + " |"));
return lines
.Aggregate((p, c) => p + Environment.NewLine + c);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment