在开发过程过程中有时候需要将List<T>泛型转换成DataTable、DataSet,可以利用反射机制将DataTable的字段与自定义类型的公开属性互相赋值。
1、List<T>泛型转换成DataTable 代码:
/// <summary> /// List<T>转换成DataTable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="dataList">集合数据</param> /// <returns>返回DataTable</returns> public static System.Data.DataTable ToDataTable<T>(this System.Collections.Generic.IList<T> list, System.Collections.Generic.IList<T> 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 代码:
/// <summary> /// List<T>转换成DataSet /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="dataList">集合数据</param> /// <returns>返回DataSet</returns> public static System.Data.DataSet ToDataSet<T>(this System.Collections.Generic.IList<T> list, System.Collections.Generic.IList<T> 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; }