您的位置:首页 > 编程语言 > C#

C#反射实现将DataTable转换为List<T>

2018-05-21 15:59 661 查看

最近工作做经常需要将datatable转换成List,如果通过foreach循环datatable.Rows转换效率很低下也很枯燥,于是写了个通过反射自动转换的代码,大大提高了效率

 

1 public static List<T> DataTableToList<T>(DataTable dt)
2 {
3      List<T> list = new List<T>();
4      foreach (DataRow row in dt.Rows)
5    {
6      T model = Activator.CreateInstance<T>();
7      Type typeinfo = typeof(T);
8       foreach (var prop in typeinfo.GetProperties())
9       {
10         if (dt.Columns.Contains(prop.Name))
11         {
12           var o = To(row[prop.Name], prop.PropertyType);
13           prop.SetValue(model, o, null);
14         }
15       }
16      list.Add(model);
17    }
18    return list;
19 }
20
21
22 /// <summary>
23 /// 将一个值转换成目标类型。
24 /// </summary>
25 public static object To(object value, Type destinationType)
26 {
27    return To(value, destinationType, CultureInfo.InvariantCulture);
28 }
29
30 /// <summary>
31 /// 将一个值转换成目标类型.
32 /// </summary>
33 public static object To(object value, Type destinationType, CultureInfo culture)
34 {
35     if (value != null)
36    {
37     var sourceType = value.GetType();
38
39     var destinationConverter = TypeDescriptor.GetConverter(destinationType);
40     if (destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType()))
41     return destinationConverter.ConvertFrom(null, culture, value);
42
43     var sourceConverter = TypeDescriptor.GetConverter(sourceType);
44     if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType))
45     return sourceConverter.ConvertTo(null, culture, value, destinationType);
46
47     if (destinationType.IsEnum && value is int)
48     return Enum.ToObject(destinationType, (int)value);
49
50     if (!destinationType.IsInstanceOfType(value))
51     return Convert.ChangeType(value, destinationType, culture);
52    }
53    return value;
54 }

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: