zoukankan      html  css  js  c++  java
  • C# DataTable转换为List

    最近工作做经常需要将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 }
  • 相关阅读:
    基础数据类型补充、集合、深浅拷贝
    python中(id,is,==,)小数据池,代码块
    字典:python的基础数据类型
    五四青年节后记
    test
    agl---atumotive grade linux开篇
    传感器
    金字塔原理
    写在2017年底
    C# 输出16进值
  • 原文地址:https://www.cnblogs.com/xiaoxiuyuan/p/9050205.html
Copyright © 2011-2022 走看看