新年将至也没啥心思工作了,打算对一下项目中常用的工具类做一个整理,温故而知新。
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 });