給DataTable添加列sql
string sql = "select * from cgpmb order by code"; DataTable dt = Bobole.Data.OracleDataRegester.GetListBySql(sql).Tables[0]; dt.Columns.Add("PCode", typeof(string)); //假如數據庫查詢出來的DataTable沒有你想要的列 Remove("")能夠刪除列 for (int i = 0; i < dt.Rows.Count; i++) { try { dt.Rows[i]["PCode"] = dt.Rows[i]["Code"].ToString().Remove(dt.Rows[i]["Code"].ToString().Length - 2, 2); } catch (Exception) { dt.Rows[i]["PCode"] = ""; } }
將DataTable轉化爲list泛型集合數據庫
public static List<T> TableToList<T>(DataTable dt, bool isStoreDB = true) { List<T> list = new List<T>(); Type type = typeof(T); //List<string> listColums = new List<string>(); PropertyInfo[] pArray = type.GetProperties(); //集合屬性數組 foreach (DataRow row in dt.Rows) { T entity = Activator.CreateInstance<T>(); //新建對象實例 foreach (PropertyInfo p in pArray) { if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value) { continue; //DataTable列中不存在集合屬性或者字段內容爲空則,跳出循環,進行下個循環 } if (isStoreDB && p.PropertyType == typeof(DateTime) && Convert.ToDateTime(row[p.Name]) < Convert.ToDateTime("1753-01-01")) { continue; } try { var obj = Convert.ChangeType(row[p.Name], p.PropertyType);//類型強轉,將table字段類型轉爲集合字段類型 p.SetValue(entity, obj, null); } catch (Exception) { // throw; } } list.Add(entity); } return list; }
將list泛型集合轉化爲DataTable數組
/// <summary> /// 轉化一個DataTable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <returns></returns> private static System.Data.DataTable ToDataTable<T>(IEnumerable<T> list) { //建立屬性的集合 List<PropertyInfo> pList = new List<PropertyInfo>(); //得到反射的入口 Type type = typeof(T); System.Data.DataTable dt = new System.Data.DataTable(); //把全部的public屬性加入到集合 並添加DataTable的列 Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); }); foreach (var item in list) { //建立一個DataRow實例 DataRow row = dt.NewRow(); //給row 賦值 pList.ForEach(p => row[p.Name] = p.GetValue(item, null)); //加入到DataTable dt.Rows.Add(row); } return dt; }