Skip to content

Commit

Permalink
Merge pull request #66 from chuongmep/main
Browse files Browse the repository at this point in the history
Add support console data from datatable
  • Loading branch information
khalidabuhakmeh authored Oct 27, 2023
2 parents c0528c9 + d901bb0 commit 2f75536
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
20 changes: 20 additions & 0 deletions ConsoleTables.Tests/ConsoleTableTest.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using Xunit;

Expand Down Expand Up @@ -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());

}
Expand Down
22 changes: 22 additions & 0 deletions src/ConsoleTables/ConsoleTable.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
Expand Down Expand Up @@ -107,6 +108,27 @@ in values.Select(value => columns.Select(column => GetColumnValue<T>(value, colu
return table;
}

public static ConsoleTable From(DataTable dataTable)
{
var table = new ConsoleTable();

var columns = dataTable.Columns
.Cast<DataColumn>()
.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();
Expand Down

0 comments on commit 2f75536

Please sign in to comment.