#region DataTable转List集合 +static IList<T> DataTableToList<T>(DataTable dt) where T : class, new() /// <summary> /// DataTable转List集合 /// </summary> /// <typeparam name="T">目标对象</typeparam> /// <param name="dt">数据表</param> /// <returns></returns> public static IList<T> DataTableToList<T>(DataTable dt) where T : class, new() { IList<T> list = new List<T>(); for (int i = 0; i < dt.Rows.Count; i++) //读取行 { T t = Activator.CreateInstance<T>(); // 创建对象实例 PropertyInfo[] propertyInfos = t.GetType().GetProperties(); // 获得对象公共属性 for (int j = 0; j < dt.Columns.Count; j++) // 读取列 { foreach (PropertyInfo info in propertyInfos) { // 属性名称和列名相同的赋值 if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper())) { // 对null值处理 if (dt.Rows[i][j] != DBNull.Value) { info.SetValue(t, dt.Rows[i][j], null); } else { info.SetValue(t, null, null); } break; // 找到对应属性赋值完毕后 跳出 继续查找下一个属性 } } } list.Add(t); // 每行结束后(即完成一个对象的赋值) 添加对象到集合中 } return list; } #endregion
DataTable转List<T>集合
猜你喜欢
转载自www.cnblogs.com/Tpf386/p/10001490.html
今日推荐
周排行