首页 > 代码库 > DataTable转换为其他对象
DataTable转换为其他对象
1.将DataTable类型的数据转换成List<T>集合
1 /// <summary> 2 /// 将DataTable类型的数据转换成List<T>集合 T实体 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="dataTable"></param> 6 /// <returns></returns> 7 public static List<T> DataTableToList<T>(DataTable dataTable) 8 { 9 List<T> list = new List<T>();10 Type targetType = typeof(T);11 PropertyInfo[] allPropertyArray = targetType.GetProperties();12 foreach (DataRow rowElement in dataTable.Rows)13 {14 T element = Activator.CreateInstance<T>();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 /// <summary> 2 /// 将DataTable的第一行转换为实体T 表转实体 3 /// </summary> 4 /// <typeparam name="T"></typeparam> 5 /// <param name="dataTable"></param> 6 /// <returns></returns> 7 public static T DataTalbeToEntity<T>(DataTable dataTable) 8 { 9 T element = Activator.CreateInstance<T>();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 /// <summary> 2 /// 根据情况对DaTaTable进行分页 3 /// </summary> 4 /// <returns></returns> 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 }
DataTable转换为其他对象
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。