/// <summary> /// Writes a table to the console. /// </summary> public static void Write <TElement>(StandardStreamWriter stream, IEnumerable <TElement> collection, IEnumerable <string> headers, string?footnotes, params Expression <Func <TElement, string> >[] values) { int columnsCount = values.Length; Func <TElement, string>[] columnFunctions = values.Select(x => x.Compile()) .ToArray(); int[] columnWidths = (from cf in columnFunctions let x = (collection.Any() ? collection.Select(cf).Max(x => x.Length) : 0) select x).ToArray(); AdjustColumnWidths(headers, columnsCount, columnWidths); int totalWidth = columnWidths.Sum() - 1 + (columnsCount) * 3; //Write top border stream.WriteBorder(totalWidth); stream.WriteTableHeader(headers, columnWidths, totalWidth); //Write table body stream.WriteTableBody(collection, columnFunctions, columnWidths); // Write bottom border and try write footnotes stream.WriteBorder(totalWidth); stream.TryWriteFootnotes(footnotes); }
/// <summary> /// Writes a table to the console. /// </summary> public static void Write <TKey, TElement>(StandardStreamWriter stream, IEnumerable <IGrouping <TKey, TElement> > collection, IEnumerable <string> headers, string?footnotes, params Expression <Func <TElement, string> >[] values) { int columnsCount = values.Length; Func <TElement, string>[] columnFunctions = values.Select(x => x.Compile()) .ToArray(); int[] columnWidths = (from cf in columnFunctions let x = (collection.Any() ? collection.SelectMany(x => x).Select(cf).Max(x => x.Length) : 0) select x).ToArray(); AdjustColumnWidths(headers, columnsCount, columnWidths); int totalWidth = columnWidths.Sum() - 1 + (columnsCount) * 3; //Write top border stream.WriteBorder(totalWidth); stream.WriteTableHeader(headers, columnWidths, totalWidth); foreach (IGrouping <TKey, TElement> group in collection) { TKey groupKey = group.Key; int countInGroup = group.Count(); stream.WriteBorder(totalWidth, '-'); stream.WithForegroundColor(ConsoleColor.DarkYellow, (o) => o.WriteLine($" {groupKey} ({countInGroup}) ".PadBoth(totalWidth))); stream.WriteBorder(totalWidth, '-'); //Write table body stream.WriteTableBody(group, columnFunctions, columnWidths); } // Write bottom border and try write footnotes stream.WriteBorder(totalWidth); stream.TryWriteFootnotes(footnotes); }
private static void WriteTableHeader(this StandardStreamWriter stream, IEnumerable <string> headers, int[] columnWidths, int totalWidth) { if (headers.Any()) { for (int i = 0; i < columnWidths.Length; ++i) { string header = headers.ElementAtOrDefault(i) ?? string.Empty; int targetWidth = columnWidths[i]; stream.Write(' '); stream.WithForegroundColor(ConsoleColor.DarkYellow, (o) => o.Write(header.PadRight(targetWidth))); if (i + 1 < columnWidths.Length) { stream.WithForegroundColor(ConsoleColor.Magenta, (o) => o.Write(" |")); } } stream.WriteLine(); //Write middle line stream.WriteBorder(totalWidth); } }