Last active
January 25, 2017 03:12
-
-
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.
This file contains hidden or 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
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