-
Notifications
You must be signed in to change notification settings - Fork 1
/
csv_Binding.cs
99 lines (95 loc) · 3.18 KB
/
csv_Binding.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataArmor
{
internal class csv_Binding
{
static public List<string> num_col = new List<string>();
static public List<string> cat_col = new List<string>();
static List<string> col_name = new List<string>();
public static DataTable csv_opening(string csvFilePath)
{
var dataTable = new DataTable();
using (StreamReader reader = new StreamReader(csvFilePath))
{
string[] headers = reader.ReadLine().Split(',');
foreach (string header in headers)
{
dataTable.Columns.Add(header, typeof(string));
col_name.Add(header);
}
while (!reader.EndOfStream)
{
string[] data = reader.ReadLine().Split(',');
dataTable.Rows.Add(data);
}
for (int i = 0; i < dataTable.Columns.Count; i++)
{
if (IsNumericColumn(dataTable, i))
{
num_col.Add(dataTable.Columns[i].ColumnName);
ConvertColumnToNumeric(dataTable, i);
}
else
{
cat_col.Add(dataTable.Columns[i].ColumnName);
}
}
}
var dataTabl = new DataTable();
using (StreamReader reader = new StreamReader(csvFilePath))
{
string[] headers = reader.ReadLine().Split(',');
foreach (string header in headers)
{
if (cat_col.Contains(header))
{
dataTabl.Columns.Add(header, typeof(string)); // Default type is string
}
else
{
dataTabl.Columns.Add(header, typeof(double));
}
}
while (!reader.EndOfStream)
{
string[] data = reader.ReadLine().Split(',');
dataTabl.Rows.Add(data);
}
}
return dataTabl;
}
static bool IsNumericColumn(DataTable dataTable, int columnIndex)
{
foreach (DataRow row in dataTable.Rows)
{
if (!IsNumeric(row[columnIndex].ToString()))
{
return false;
}
}
return true;
}
static bool IsNumeric(string value)
{
double result;
return double.TryParse(value, out result);
}
static void ConvertColumnToNumeric(DataTable dataTable, int columnIndex)
{
foreach (DataRow row in dataTable.Rows)
{
double value;
if (double.TryParse(row[columnIndex].ToString(), out value))
{
row[columnIndex] = value;
}
}
}
}
}