1 /// <summary>
2 /// Datatable转为模型
3 /// </summary>
4 /// <typeparam name="T"></typeparam>
5 /// <param name="dt"></param>
6 /// <returns></returns>
7 public static IEnumerable<T> DataTableToModel<T>(DataTable dt)
8 where T : new()
9 {
10 Type type = typeof(T);
11 List<T> list = new List<T>();
12 List<PropertyInfo> properties = new List<PropertyInfo>();
13 foreach (PropertyInfo info in type.GetProperties())
14 {
15 if (info.PropertyType.IsValueType || info.PropertyType == typeof(string))
16 {
17 properties.Add(info);
18 }
19 }
20 foreach (DataRow dr in dt.Rows)
21 {
22 T t = new T();
23 for (int i = 0; i < properties.Count; i++)
24 {
25 if (dt.Columns.Contains(properties[i].Name))
26 {
27 properties[i].SetValue(t, dr[properties[i].Name] != DBNull.Value ? dr[properties[i].Name] : "");
28 }
29 }
30 list.Add(t);
31 }
32 return list;
33 }