DataTable所有数据转换成实体类列表

需要注意:此方法必须新建一个实体类文件,刚好对应你的DataTable所有列名字

 1  /// <summary>
 2  /// DataTable所有数据转换成实体类列表
 3  /// </summary>
 4  /// <typeparam name="T">实体类</typeparam>
 5  /// <param name="dt">DataTable</param>
 6  /// <returns>返回实体类列表</returns>
 7  public static List<T> DataTableToList<T>(DataTable dt) where T : new()
 8  {
 9      if (dt == null || dt.Rows.Count == 0)
10      {
11          return new List<T>();
12      }
13      // 实例化实体类和列表
14      List<T> list = new List<T>();
15      // 获取所有列
16      DataColumnCollection columns = dt.Columns;
17      foreach (DataRow dr in dt.Rows)
18      {
19          T t = new T();
20          // 获得实体类的所有公共属性
21          PropertyInfo[] propertys = t.GetType().GetProperties();
22 
23          //循环比对且赋值
24          foreach (PropertyInfo pi in propertys)
25          {
26              string name = pi.Name;
27              Type targetType = pi.PropertyType;
28              Type convertType = targetType;
29              // 检查DataTable是否包含此列    
30              if (columns.Contains(name))
31              {
32                  if (!pi.CanWrite) continue;
33 
34                  object value = dr[name];
35                  if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
36                  {
37                      //可空类型
38                      NullableConverter nullableConverter = new NullableConverter(targetType);
39                      convertType = nullableConverter.UnderlyingType;
40                  }
41                  if (!string.IsNullOrEmpty(convertType.FullName) && !string.IsNullOrEmpty(value?.ToString()))
42                  {
43                      value = Convert.ChangeType(value, convertType);
44                  }
45                  if (value != DBNull.Value)
46                  {
47                      //是否需要转化
48                      //if (value is int || value is float || value is decimal || value is double)
49                      //{
50                      //    p.SetValue(t, value.ToString(), null);
51                      //}
52                      //else
53                      //{
54                      //    p.SetValue(t, value, null);
55                      //}
56                      pi.SetValue(t, value, null);
57                  }
58              }
59          }
60          list.Add(t);
61      }
62      return list;
63  }

转载请注明出处,谢谢!

posted @ 2025-10-29 12:39  官方小可爱  阅读(4)  评论(0)    收藏  举报