DataTable转换为其他对象
Posted 凌云卧星
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 else 26 { 27 property.SetValue(element, rowElement 28 [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 else 26 { 27 property.SetValue(element, rowElement 28 [columnElement.ColumnName], null); 29 } 30 } 31 } 32 } 33 } 34 else 35 { 36 return default(T);//返回null 37 } 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转换为其他对象的主要内容,如果未能解决你的问题,请参考以下文章