1. 程式人生 > >DataTable轉List<T>集合

DataTable轉List<T>集合

 

#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