zoukankan      html  css  js  c++  java
  • C#j将DataTable转换成List

     1   public class ModelConvertHelper<T> where T : new()
     2     {
     3 
     4         /// <summary>
     5         /// Convert To Model
     6         /// </summary>
     7         /// <param name="dt">Datatable for convert</param>
     8         /// <returns>Collection of model</returns>
     9         public static IList<T> ConvertToModel(DataTable dt)
    10         {
    11             // Collection definition
    12             IList<T> ts = new List<T>();
    13 
    14             // Get model type
    15             Type type = typeof(T);
    16 
    17             string tempName = "";
    18 
    19             foreach (DataRow dr in dt.Rows)
    20             {
    21                 T t = new T();
    22 
    23                 // Get property of model
    24                 PropertyInfo[] propertys = t.GetType().GetProperties();
    25 
    26                 foreach (PropertyInfo pi in propertys)
    27                 {
    28                     tempName = pi.Name;
    29 
    30                     // check column is exsit
    31                     if (dt.Columns.Contains(tempName))
    32                     {
    33                         // Whether can be set value
    34                         if (!pi.CanWrite) continue;
    35 
    36                         object value = dr[tempName];
    37                         if (value != DBNull.Value)
    38                         {
    39                             try
    40                             {
    41                                 pi.SetValue(t, value, null);
    42                             }
    43                             catch (Exception)
    44                             {
    45                                 pi.SetValue(t, value.ToString(), null);
    46                             }
    47                         }
    48                     }
    49                 }
    50 
    51                 ts.Add(t);
    52             }
    53 
    54             return ts;
    55         }
    56 
    57     }
  • 相关阅读:
    大数据之 Spark
    设计模式之——外观or门面模式
    架构设计
    Spring
    高并发系列之——负载均衡,web负载均衡
    高并发系列之——原子性和可见性
    高并发系列之——缓存中间件Redis
    mybatis
    JVM读书笔记
    mybatis中一对一关系映射
  • 原文地址:https://www.cnblogs.com/lewisli/p/3449718.html
Copyright © 2011-2022 走看看