From 814762816876cb50913742cb1a3bfdc2e40cf2a1 Mon Sep 17 00:00:00 2001 From: Steven Date: Thu, 22 Aug 2024 17:51:12 -0400 Subject: [PATCH] Start working on a DataTableParser --- CSharp.Nixill/src/Grid/CSVParser.cs | 2 +- CSharp.Nixill/src/Grid/DataTableParser.cs | 60 +++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 CSharp.Nixill/src/Grid/DataTableParser.cs diff --git a/CSharp.Nixill/src/Grid/CSVParser.cs b/CSharp.Nixill/src/Grid/CSVParser.cs index d4eed19..4776abc 100644 --- a/CSharp.Nixill/src/Grid/CSVParser.cs +++ b/CSharp.Nixill/src/Grid/CSVParser.cs @@ -26,7 +26,7 @@ namespace Nixill.Collections.Grid.CSV /// /// /// - public class CSVParser + public static class CSVParser { /// /// Reads a CSV file into a Grid of strings. diff --git a/CSharp.Nixill/src/Grid/DataTableParser.cs b/CSharp.Nixill/src/Grid/DataTableParser.cs new file mode 100644 index 0000000..b1cf267 --- /dev/null +++ b/CSharp.Nixill/src/Grid/DataTableParser.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.IO; +using Nixill.Utils; + +namespace Nixill.Collections.Grid.CSV; + +/// +/// This class contains static methods to convert between DataTables and +/// comma separated value format files and text. +/// +public static class DataTableCSVParser +{ + public static DataTable FileToDataTable(string path, IDictionary columnDefs = null, + IDictionary> deserializers = null, IEnumerable primaryKey = null) + => EnumerableToDataTable(FileUtils.FileCharEnumerator(path), columnDefs, deserializers, primaryKey); + + public static DataTable StreamToDataTable(StreamReader reader, IDictionary columnDefs = null, + IDictionary> deserializers = null, IEnumerable primaryKey = null) + => EnumerableToDataTable(FileUtils.StreamCharEnumerator(reader), columnDefs, deserializers, primaryKey); + + public static DataTable EnumerableToDataTable(IEnumerable input, + IDictionary columnDefs = null, IDictionary> deserializers = null, + IEnumerable primaryKey = null) + { + DataTable table = new(); + + columnDefs ??= new Dictionary(); + deserializers ??= new Dictionary>(); + + var types = new List(); + + IEnumerable> rows = CSVParser.EnumerableToRows(input); + bool isHeaderRow = true; + + foreach (var row in rows) + { + if (isHeaderRow) + { + foreach (string item in row) + { + if (columnDefs.TryGetValue(item, out DataColumn col)) + { + table.Columns.Add(col); + types.Add(col.DataType); + } + else + { + table.Columns.Add(new DataColumn + { + ColumnName = item + }); + types.Add(typeof(string)); + } + } + } + } + } +} \ No newline at end of file