DataTable、實體類Model和泛型List之間的轉化


1.網上例子

http://www.2cto.com/kf/201204/127785.html

Serialize() 和getSendDetailTest()

 

2.研發中例子

dt轉化成model

dt轉化model Code
 1  public static object GetModel(DataTable dt, object model)
 2         {
 3 
 4             foreach (DataRow row in dt.Rows)
 5             {
 6                 foreach (var item in model.GetType().GetProperties())
 7                 {
 8                     if (row.Table.Columns.Contains(item.Name))
 9                     {
10                         if (DBNull.Value != row[item.Name])
11                         {
12                             item.SetValue(model, Convert.ChangeType(row[item.Name], item.PropertyType), null);
13                         }
14 
15                     }
16                 }
17             }
18             return model;
19         }

model 經過list 轉化成dt

View Code
List<Sys_grade> list = new List<Sys_grade>();
                        list.Add(grade);
                        DataTable dtgrade = new DataTable();
                        dtgrade = KeyValueHelper.ListToDataTable(list);
                        daclient.SysGradeAdd(dtgrade);

ListToDataTable()方法:

View Code
 1   public static DataTable ListToDataTable<T>(List<T> entitys)
 2         {
 3 
 4             //檢查實體集合不能為空
 5             if (entitys == null || entitys.Count < 1)
 6             {
 7                 return new DataTable();
 8             }
 9 
10             //取出第一個實體的所有Propertie
11             Type entityType = entitys[0].GetType();
12             PropertyInfo[] entityProperties = entityType.GetProperties();
13 
14             //生成DataTable的structure
15             //生產代碼中,應將生成的DataTable結構Cache起來,此處略
16             DataTable dt = new DataTable("dt");
17             for (int i = 0; i < entityProperties.Length; i++)
18             {
19                 //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
20                 dt.Columns.Add(entityProperties[i].Name);
21             }
22 
23             //將所有entity添加到DataTable中
24             foreach (object entity in entitys)
25             {
26                 //檢查所有的的實體都為同一類型
27                 if (entity.GetType() != entityType)
28                 {
29                     throw new Exception("要轉換的集合元素類型不一致");
30                 }
31                 object[] entityValues = new object[entityProperties.Length];
32                 for (int i = 0; i < entityProperties.Length; i++)
33                 {
34                     entityValues[i] = entityProperties[i].GetValue(entity, null);
35 
36                 }
37                 dt.Rows.Add(entityValues);
38             }
39             return dt;
40         }

 

備注:List<>:表示可通過索引訪問的對象的強類型列表。 提供用於對列表進行搜索、排序和操作的方法。

最后:感謝網友提供資料。


免責聲明!

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



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