1.将DataTable类型的数据转换成List<T>集合
1 ///2 /// 将DataTable类型的数据转换成List 4 ///集合 T实体 3 /// 5 /// 6 /// 7 public static List DataTableToList (DataTable dataTable) 8 { 9 List list = new List ();10 Type targetType = typeof(T);11 PropertyInfo[] allPropertyArray = targetType.GetProperties();12 foreach (DataRow rowElement in dataTable.Rows)13 {14 T element = Activator.CreateInstance ();15 foreach (DataColumn columnElement in dataTable.Columns)16 {17 foreach (PropertyInfo property in allPropertyArray)18 {19 if (property.Name.Equals(columnElement.ColumnName))20 {21 if (rowElement[columnElement.ColumnName] == DBNull.Value)22 {23 property.SetValue(element, null, null);24 }25 else26 {27 property.SetValue(element, rowElement28 [columnElement.ColumnName], null);29 }30 }31 }32 }33 list.Add(element);34 }35 return list;36 }
2.将DataTable的第一行转换为实体T 表转实体
1 ///2 /// 将DataTable的第一行转换为实体T 表转实体 3 /// 4 ///5 /// 6 /// 7 public static T DataTalbeToEntity (DataTable dataTable) 8 { 9 T element = Activator.CreateInstance ();10 Type targetType = typeof(T);11 PropertyInfo[] allPropertyArray = targetType.GetProperties();12 if (dataTable != null && dataTable.Rows.Count > 0)13 {14 DataRow rowElement = dataTable.Rows[0];15 foreach (DataColumn columnElement in dataTable.Columns)16 {17 foreach (PropertyInfo property in allPropertyArray)18 {19 if (property.Name.Equals(columnElement.ColumnName))20 {21 if (rowElement[columnElement.ColumnName] == DBNull.Value)22 {23 property.SetValue(element, null, null);24 }25 else26 {27 property.SetValue(element, rowElement28 [columnElement.ColumnName], null);29 }30 }31 }32 }33 }34 else35 {36 return default(T);//返回null37 }38 return element;39 }
3.根据情况对DaTaTable进行分页
1 ///2 /// 根据情况对DaTaTable进行分页 3 /// 4 ///5 public static DataTable GetPageTable(DataTable dt, int CurrentPageIndex, int PageSize, ref int RecordCount) 6 { 7 DataTable newdt = dt.Clone(); 8 RecordCount = dt.Rows.Count; 9 for (int i = (CurrentPageIndex - 1) * PageSize; i < CurrentPageIndex * PageSize; i++)10 {11 if (i < RecordCount)12 {13 newdt.Rows.Add(dt.Rows[i].ItemArray);14 }15 }16 return newdt;17 }