From d901bb0dead4afeb48d4e082917d333b197d8c8d Mon Sep 17 00:00:00 2001 From: chuongmep <31106432+chuongmep@users.noreply.github.com> Date: Tue, 29 Aug 2023 23:10:15 +0800 Subject: [PATCH] add support datatable --- ConsoleTables.Tests/ConsoleTableTest.cs | 20 ++++++++++++++++++++ src/ConsoleTables/ConsoleTable.cs | 22 ++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/ConsoleTables.Tests/ConsoleTableTest.cs b/ConsoleTables.Tests/ConsoleTableTest.cs index fdf80c4..974b382 100644 --- a/ConsoleTables.Tests/ConsoleTableTest.cs +++ b/ConsoleTables.Tests/ConsoleTableTest.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Data; using System.IO; using Xunit; @@ -174,6 +175,25 @@ public void TestDictionaryTable() | A | True | False | True | | B | False | True | False | | C | False | False | True | +",table.ToMarkDownString()); + + } + [Fact] + public void TestDataTable() + { + DataTable data = new DataTable(); + data.Columns.Add("A", typeof(bool)); + data.Columns.Add("B", typeof(bool)); + data.Columns.Add("C", typeof(bool)); + data.Rows.Add(true, false, true); + data.Rows.Add(false, true, false); + data.Rows.Add(false, false, true); + var table = ConsoleTable.From(data); + Assert.Equal(@"| A | B | C | +|-------|-------|-------| +| True | False | True | +| False | True | False | +| False | False | True | ",table.ToMarkDownString()); } diff --git a/src/ConsoleTables/ConsoleTable.cs b/src/ConsoleTables/ConsoleTable.cs index e2c2df6..2b904cf 100644 --- a/src/ConsoleTables/ConsoleTable.cs +++ b/src/ConsoleTables/ConsoleTable.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Data; using System.IO; using System.Linq; using System.Text; @@ -107,6 +108,27 @@ in values.Select(value => columns.Select(column => GetColumnValue(value, colu return table; } + public static ConsoleTable From(DataTable dataTable) + { + var table = new ConsoleTable(); + + var columns = dataTable.Columns + .Cast() + .Select(x => x.ColumnName) + .ToList(); + + table.AddColumn(columns); + + foreach (DataRow row in dataTable.Rows) + { + var items = row.ItemArray.Select(x => x is byte[] data ? Convert.ToBase64String(data) : x.ToString()) + .ToArray(); + table.AddRow(items); + } + + return table; + } + public override string ToString() { var builder = new StringBuilder();