【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; }  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM