• C# DataTable 和List之间相互转换的方法


    一、DataTable转换到List

    方法1.

     1 /// <summary>    
     2     /// 实体转换辅助类    
     3     /// </summary>    
     4     public class ModelConvertHelper
     5     {
     6         /// <summary>
     7         /// DataTable转换到List
     8         /// </summary>
     9         /// <typeparam name="T"></typeparam>
    10         /// <param name="table"></param>
    11         /// <returns></returns>
    12         public static IList<T> ConvertTo<T>(DataTable table)
    13         {
    14             if (table == null)
    15             {
    16                 return null;
    17             }
    18 
    19             List<DataRow> rows = new List<DataRow>();
    20 
    21             foreach (DataRow row in table.Rows)
    22             {
    23                 rows.Add(row);
    24             }
    25 
    26             return ConvertTo<T>(rows);
    27         }
    28 
    29         public static IList<T> ConvertTo<T>(IList<DataRow> rows)
    30         {
    31             IList<T> list = null;
    32 
    33             if (rows != null)
    34             {
    35                 list = new List<T>();
    36 
    37                 foreach (DataRow row in rows)
    38                 {
    39                     T item = CreateItem<T>(row);
    40                     list.Add(item);
    41                 }
    42             }
    43 
    44             return list;
    45         }
    46 
    47         public static T CreateItem<T>(DataRow row)
    48         {
    49             T obj = default(T);
    50             if (row != null)
    51             {
    52                 obj = Activator.CreateInstance<T>();
    53 
    54                 foreach (DataColumn column in row.Table.Columns)
    55                 {
    56                     PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
    57                     try
    58                     {
    59                         object value = row[column.ColumnName];
    60                         prop.SetValue(obj, value, null);
    61                     }
    62                     catch
    63                     {  //You can log something here     
    64                         //throw;    
    65                     }
    66                 }
    67             }
    68 
    69             return obj;
    70         }
    71 
    72 
    73        
    74     } 

    方法2.

     1  public class ModelConvertHelper<T> where   T : new()    
     2      {    
     3         public static IList<T> ConvertToModel(DataTable dt)    
     4          {    
     5             // 定义集合    
     6              IList<T> ts = new List<T>(); 
     7      
     8             // 获得此模型的类型   
     9              Type type = typeof(T);      
    10             string tempName = "";      
    11       
    12             foreach (DataRow dr in dt.Rows)      
    13              {    
    14                  T t = new T();     
    15                 // 获得此模型的公共属性      
    16                  PropertyInfo[] propertys = t.GetType().GetProperties(); 
    17                 foreach (PropertyInfo pi in propertys)      
    18                  {      
    19                      tempName = pi.Name;  // 检查DataTable是否包含此列    
    20    
    21                     if (dt.Columns.Contains(tempName))      
    22                      {      
    23                         // 判断此属性是否有Setter      
    24                         if (!pi.CanWrite) continue;         
    25    
    26                         object value = dr[tempName];      
    27                         if (value != DBNull.Value)      
    28                              pi.SetValue(t, value, null);  
    29                      }     
    30                  }      
    31                  ts.Add(t);      
    32              }     
    33             return ts;     
    34          }     
    35      }    

    使用方式:  

    1 // 获得查询结果  
    2 DataTable dt = DbHelper.ExecuteDataTable(...);  
    3 // 把DataTable转换为IList<UserInfo>  
    4 IList<UserInfo> users = ModelConvertHelper<UserInfo>.ConvertToModel(dt);

    二、List<T>/IEnumerable转换到DataTable/DataView

    方法一

     1 /// <summary>
     2 /// Convert a List{T} to a DataTable.
     3 /// </summary>
     4 private DataTable ToDataTable<T>(List<T> items)
     5 {
     6     var tb = new DataTable(typeof (T).Name);
     7  
     8     PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
     9  
    10     foreach (PropertyInfo prop in props)
    11     {
    12         Type t = GetCoreType(prop.PropertyType);
    13         tb.Columns.Add(prop.Name, t);
    14     }
    15  
    16     foreach (T item in items)
    17     {
    18         var values = new object[props.Length];
    19  
    20         for (int i = 0; i < props.Length; i++)
    21         {
    22             values[i] = props[i].GetValue(item, null);
    23         }
    24  
    25         tb.Rows.Add(values);
    26     }
    27  
    28     return tb;
    29 }
    30  
    31 /// <summary>
    32 /// Determine of specified type is nullable
    33 /// </summary>
    34 public static bool IsNullable(Type t)
    35 {
    36     return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
    37 }
    38  
    39 /// <summary>
    40 /// Return underlying type if type is Nullable otherwise return the type
    41 /// </summary>
    42 public static Type GetCoreType(Type t)
    43 {
    44     if (t != null && IsNullable(t))
    45     {
    46         if (!t.IsValueType)
    47         {
    48             return t;
    49         }
    50         else
    51         {
    52             return Nullable.GetUnderlyingType(t);
    53         }
    54     }
    55     else
    56     {
    57         return t;
    58     }
    59 }

    方法二

     1 public static DataTable ToDataTable<T>(IEnumerable<T> collection)
     2  {
     3      var props = typeof(T).GetProperties();
     4      var dt = new DataTable();
     5      dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
     6      if (collection.Count() > 0)
     7      {
     8          for (int i = 0; i < collection.Count(); i++)
     9          {
    10              ArrayList tempList = new ArrayList();
    11              foreach (PropertyInfo pi in props)
    12              {
    13                  object obj = pi.GetValue(collection.ElementAt(i), null);
    14                  tempList.Add(obj);
    15              }
    16              object[] array = tempList.ToArray();
    17              dt.LoadDataRow(array, true);
    18          }
    19      }
    20      return dt;
    21  }

     转载自http://www.okbase.net/doc/details/3282

  • 相关阅读:
    VLC通过RTSP地址向IPC取流播放不了问题排查
    linux opt分区扩容操作案例
    win10远程桌面报错"出现身份验证错误"
    linux通过expect实现脚本自动交互
    oracle通过触发器记录登陆主机ip
    linux root密码忘记重置
    linux双网卡配置
    Tomcat报错合集
    UFT(QTP)中的Object Repository
    利用JAVA反射机制设计通用的DAO
  • 原文地址:https://www.cnblogs.com/lijianhong90/p/4171092.html
Copyright © 2020-2023  润新知