首页 > 代码库 > DataTable和List集合互转

DataTable和List集合互转

 1 /// <summary>
 2         /// 将集合转换成DataTable
 3         /// </summary>
 4         /// <param name="list">集合</param>
 5         /// <returns></returns>
 6         public static DataTable ToDataTable(IList list)
 7         {
 8             DataTable result = new DataTable();
 9             if (list.Count > 0)
10             {
11                 PropertyInfo[] propertys = list[0].GetType().GetProperties();
12                 foreach (PropertyInfo pi in propertys)
13                 {
14                     result.Columns.Add(pi.Name, pi.PropertyType);
15                 }
16                 for (int i = 0; i < list.Count; i++)
17                 {
18                     ArrayList tempList = new ArrayList();
19                     foreach (PropertyInfo pi in propertys)
20                     {
21                         object obj = pi.GetValue(list[i], null);
22                         tempList.Add(obj);
23                     }
24                     object[] array = tempList.ToArray();
25                     result.LoadDataRow(array, true);
26                 }
27             }
28             return result;
29         }
30  
31  
32  
33     /// <summary>
34         /// 讲DataTable转换成集合
35         /// </summary>
36         /// <param name="dt">数据表</param>
37         /// <returns></returns>
38         public static IList<CarNum> ToList(DataTable dt)
39         {
40             // 定义集合
41             IList<CarNum> ts = new List<CarNum>();
42  
43             // 获得此模型的类型
44             Type type = typeof(CarNum);
45  
46             string tempName = "";
47  
48             foreach (DataRow dr in dt.Rows)
49             {
50                 CarNum t = new CarNum();
51  
52                 // 获得此模型的公共属性
53                 PropertyInfo[] propertys = t.GetType().GetProperties();
54  
55                 foreach (PropertyInfo pi in propertys)
56                 {
57                     tempName = pi.Name;
58  
59                     // 检查DataTable是否包含此列
60                     if (dt.Columns.Contains(tempName))
61                     {
62                         // 判断此属性是否有Setter
63                         if (!pi.CanWrite) continue;
64  
65                         object value =http://www.mamicode.com/ dr[tempName];
66                         if (value != DBNull.Value)
67                             pi.SetValue(t, value, null);
68                     }
69                 }
70  
71                 ts.Add(t);
72             }
73  
74             return ts;
75  
76         }
View Code