DataTable轉換list泛型集合(反射)

憤怒的TryCatch發表於2015-12-01
一個簡單的擴充套件,用於將DataTable轉換成List<T>型別的泛型集合:
 1 /// <summary>
 2         /// DataTable轉換list泛型(反射)
 3         /// </summary>
 4         /// <typeparam name="T">目標實體</typeparam>
 5         /// <param name="dt">源資料表</param>
 6         /// <returns>List型別的泛型集合</returns>
 7         public static List<T> ToList<T>(this DataTable dt)
 8         {
 9             var list = new List<T>();
10             Type t = typeof (T);
11             var plist = new List<PropertyInfo>(typeof(T).GetProperties());
12             foreach (DataRow item in dt.Rows)
13             {
14                 T s = Activator.CreateInstance<T>();
15                 for (int i = 0; i < dt.Columns.Count; i++)
16                 {
17                     PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
18                     if (info != null)
19                     {
20                         if (!Convert.IsDBNull(item[i]))
21                         {
22                             info.SetValue(s, item[i], null);
23                         }
24                     }
25                 }
26                 list.Add(s);
27             }
28             return list;
29         }

 

相關文章