【C#經常使用方法】1.DataTable與List的相互轉換

 


 

DataTable與List<T>互轉

1.List<T>轉DataTable


 

public static DataTable ListToDataTable<T>(List<T> list) { if(list==null || list.Count==0) { return new DataTable(); } //獲取T下全部的屬性
    Type entityType = list[0].GetType(); PropertyInfo[] entityProperties = entityType.GetProperties(); DataTable dt = new DataTable("data"); for(int i=0; i<entityProperties.Length; i++) { dt.Columns.Add(entityProperties[i].Name); } foreach (var item in list) { if(item.GetType() != entityType) { throw new Exception("要轉換集合元素類型不一致!") } //建立一個用於放全部屬性值的數組
        object[] entityValues = new object[entityProperties.Length]; for(int i=0; i<entityProperties.Length; i++) { entityValues[i] = entityProperties[i].GetValue(item, null); } dt.Rows.Add(entityValues) } return dt; }

 

2.DataTable轉List<T>


 

public static IList<T> ConvertToModel(DataTable dt) { // 定義集合 
    IList<T> ts = new List<T>(); // 得到此模型的類型 
    Type type = typeof(T); string tempName = ""; foreach (DataRow dr in dt.Rows) { T t = new T(); // 得到此模型的公共屬性 
        PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { tempName = pi.Name;  // 檢查DataTable是否包含此列 
           if (dt.Columns.Contains(tempName)) { // 判斷此屬性是否有Setter 
               if (!pi.CanWrite) continue; object value = dr[tempName]; if (value != DBNull.Value) pi.SetValue(t, value, null); } } ts.Add(t); } return ts; }