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 }
  • 相关阅读:
    SQLServer分组加序号,只取某个对象指定条件的前几个
    SQLServer用with temptb AS临时表查询或者更新字段,将某个字段赋值成某个字段的值
    KMP算法
    java知识点
    程序接口设计的六大原则
    罗马数字转int
    使用github作为maven仓库存放发布自己的jar包依赖 实现多个项目公共部分代码的集中,避免团队中多个项目之间代码的复制粘贴
    java mybatis中大于号小于号的转义
    两个有序数组 A1 A2 的合并
    Mysql_设置root指定的ip访问或连接数据库
  • 原文地址:https://www.cnblogs.com/xiaoxiuyuan/p/9050205.html
Copyright © 2011-2022 走看看