在开发过程过程中有时候需要将List<T>泛型转换成DataTable、DataSet,可以利用反射机制将DataTable的字段与自定义类型的公开属性互相赋值。
1、List<T>泛型转换成DataTable 代码:
////// List ///转换成DataTable /// /// /// 集合数据 /// 返回DataTable public static System.Data.DataTable ToDataTable(this System.Collections.Generic.IList list, System.Collections.Generic.IList dataList) where T : class ,new() { if (dataList == null || !dataList.Any()) { return null; } Type type = typeof(T); System.Data.DataTable dt = new System.Data.DataTable(type.Name); System.Reflection.PropertyInfo[] propertyInfoArray = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); foreach (T t in dataList.Where(t => t != null)) { System.Data.DataRow row = dt.NewRow(); for (int i = 0, j = propertyInfoArray.Length; i < j; i++) { System.Reflection.PropertyInfo propertyInfo = propertyInfoArray[i]; string name = propertyInfo.Name; if (dt.Columns[name] == null) { System.Data.DataColumn column = new System.Data.DataColumn(name, propertyInfo.PropertyType); dt.Columns.Add(column); } row[name] = propertyInfo.GetValue(t, null); } dt.Rows.Add(row); } return dt; }
2、List<T>泛型转换成DataSet 代码:
////// List ///转换成DataSet /// /// /// 集合数据 /// 返回DataSet public static System.Data.DataSet ToDataSet(this System.Collections.Generic.IList list, System.Collections.Generic.IList dataList) where T : class ,new() { if (dataList == null || !dataList.Any()) { return null; } Type type = typeof(T); System.Data.DataSet ds = new System.Data.DataSet(); System.Data.DataTable dt = new System.Data.DataTable(type.Name); System.Reflection.PropertyInfo[] propertyInfoArray = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); foreach (T t in dataList.Where(t => t != null)) { System.Data.DataRow row = dt.NewRow(); for (int i = 0, j = propertyInfoArray.Length; i < j; i++) { System.Reflection.PropertyInfo propertyInfo = propertyInfoArray[i]; string name = propertyInfo.Name; if (dt.Columns[name] == null) { System.Data.DataColumn column = new System.Data.DataColumn(name, propertyInfo.PropertyType); dt.Columns.Add(column); } row[name] = propertyInfo.GetValue(t, null); } dt.Rows.Add(row); } ds.Tables.Add(dt); return ds; }