新年將至也沒啥心思工作了,打算對一下項目中常用的工具類做一個整理,溫故而知新。
1 public static class DataTableExtensions
2 { 3 4 /// <summary> 5 /// List 轉換成Datatable 6 /// </summary> 7 /// <typeparam name="T"></typeparam> 8 /// <param name="t"></param> 9 /// <returns></returns> 10 public delegate object[] CreateRowDelegate<T>(T t); 11 static public DataTable ToDataTable<T>(this IEnumerable<T> varlist, CreateRowDelegate<T> fn) 12 { 13 //存表的列名 14 DataTable dtReturn = new DataTable(); 15 16 // 訪問屬性元素 17 PropertyInfo[] oProps = null; 18 19 // 判斷屬性元素大於0就遍歷 20 21 foreach (T rec in varlist) 22 { 23 24 // 用反射來獲取屬性名,創建表,只執行第一次 25 if (oProps == null) 26 { 27 //得到公有屬性 28 oProps = ((Type)rec.GetType()).GetProperties(); 29 //遍歷屬性中的數據 30 foreach (PropertyInfo pi in oProps) 31 { 32 //獲取屬性的名稱與類型 33 34 35 Type colType = pi.PropertyType; 36 37 if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) 38 { 39 40 colType = colType.GetGenericArguments()[0]; 41 42 } 43 44 dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); 45 46 } 47 48 } 49 //將數據填充到行中 50 DataRow dr = dtReturn.NewRow(); 51 foreach (PropertyInfo pi in oProps) 52 { 53 54 dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null); 55 56 } 57 58 dtReturn.Rows.Add(dr); 59 60 } 61 62 return (dtReturn); 63 64 } 65 66 }
調用:
DataTable dt = DataTableExtensions.ToDataTable(list, c => new object[] { list });