Skip to content

Instantly share code, notes, and snippets.

@hoganlong
Last active March 15, 2026 15:57
Show Gist options
  • Select an option

  • Save hoganlong/eac97f171c7afb02430f8c514ec28554 to your computer and use it in GitHub Desktop.

Select an option

Save hoganlong/eac97f171c7afb02430f8c514ec28554 to your computer and use it in GitHub Desktop.
Fix some formatting stuffs
using System.Data;
namespace MyExtensions
{
public static class DataTableExtensions
{
public static void PrintToConsoleAligned(this DataTable dt)
{
if (dt == null) return;
// 1. Calculate maximum column widths
var columnWidths = dt.Columns.Cast<DataColumn>()
.Select(col =>
Math.Max(col.ColumnName.Length, dt.AsEnumerable()
.Select(row => row[col].ToString() ?? "") // get non-null
.Max(str => str.Length))) // find the longest
.ToList(); // make column list
// 2. Print the header row
for (int i = 0; i < dt.Columns.Count; i++)
{
Console.Write(dt.Columns[i].ColumnName.PadRight(columnWidths[i] + 2)); // Add 2 for spacing
}
Console.WriteLine();
Console.WriteLine(new string('-', columnWidths.Sum() + (columnWidths.Count * 2)));
// 3. Print the data rows
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
string x = row[i].ToString() ?? "";
// Align left using PadRight
Console.Write(x.PadRight(columnWidths[i] + 2));
}
Console.WriteLine();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment