IEnumerable<T>轉DataTable,為空怎麼辦?
阿新 • • 發佈:2020-07-31
1 public static class DataConvertor
2 {
3 public static DataTable ToDataTable<T>(IEnumerable<T> data)
4 {
5 PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
6 var table = new DataTable();
7 foreach (PropertyDescriptor prop in properties)
8 table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
9 foreach (T item in data)
10 {
11 DataRow row = table.NewRow();
12 foreach (PropertyDescriptor prop in properties)
13 row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
14 table.Rows.Add(row);
15 }
16 return table;
17 }
18
19 public static DataTable ToDataTable(IRfcTable rfcTable)
20 {
21 DataTable table = new DataTable();
22 int liElement = 0;
23 for (liElement = 0; liElement <= rfcTable.ElementCount - 1; liElement++)
24 {
25 RfcElementMetadata metadata = rfcTable.GetElementMetadata(liElement);
26 table.Columns.Add(metadata.Name); //迴圈建立列
27 }
28 foreach (IRfcStructure dr in rfcTable) //迴圈table結構表
29 {
30 DataRow row = table.NewRow(); //建立新行
31 for (liElement = 0; liElement <= rfcTable.ElementCount - 1; liElement++)
32 {
33 RfcElementMetadata metadata = rfcTable.GetElementMetadata(liElement);
34 row[metadata.Name] = dr.GetString(metadata.Name).Trim();
35 }
36 table.Rows.Add(row);
37 }
38
39 return table;
40 }
41 }