• C#中Datatable和List互相转换


      其实早就该写的,哈哈,不过今天刚想起来注册,热热手,就写一下,哈哈。

      直接上内容吧:

      建立一个控制台应用程序,

     1             List<students> Studentlist =
     2             new List<students>{
     3                 new students{ Name = "zhagnsan1", Chinese = 101, Math = 90, English = 80 },
     4                 new students{ Name = "zhagnsan2", Chinese = 102, Math = 90, English = 80 },
     5                 new students{ Name = "zhagnsan3", Chinese = 103, Math = 90, English = 80 }
     6             };
     7             DataTable dt = ListToDatatableHelper.ToDataTable(Studentlist);
     8             this.dataGridView1.DataSource = dt;
     9 
    10             List<students> list = DatatableToListHelper.ConvertToList(dt);
    11 
    12           public class students
    13           {
    14             public string Name { get; set; }
    15             public double English { get; set; }
    16             public double Chinese { get; set; }
    17             public double Math { get; set; }
    18           }

      ListToDatatableHelper.cs中的内容为:

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Data;
      4 using System.Linq;
      5 using System.Reflection;
      6 using System.Text;
      7 using System.Threading.Tasks;
      8 
      9 namespace ListToDatatable
     10 {
     11     public class ListToDatatableHelper
     12     {
     13         /// <summary>
     14         /// Convert a List{T} to a DataTable.
     15         /// </summary>
     16         public static DataTable ToDataTable<T>(List<T> items)
     17         {
     18             var tb = new DataTable(typeof(T).Name);
     19 
     20             PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
     21 
     22             foreach (PropertyInfo prop in props)
     23             {
     24                 Type t = GetCoreType(prop.PropertyType);
     25                 tb.Columns.Add(prop.Name, t);
     26             }
     27 
     28             foreach (T item in items)
     29             {
     30                 var values = new object[props.Length];
     31 
     32                 for (int i = 0; i < props.Length; i++)
     33                 {
     34                     values[i] = props[i].GetValue(item, null);
     35                 }
     36 
     37                 tb.Rows.Add(values);
     38             }
     39 
     40             return tb;
     41         }
     42 
     43         /// <summary>
     44         /// Determine of specified type is nullable
     45         /// </summary>
     46         public static bool IsNullable(Type t)
     47         {
     48             return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
     49         }
     50 
     51         /// <summary>
     52         /// Return underlying type if type is Nullable otherwise return the type
     53         /// </summary>
     54         public static Type GetCoreType(Type t)
     55         {
     56             if (t != null && IsNullable(t))
     57             {
     58                 if (!t.IsValueType)
     59                 {
     60                     return t;
     61                 }
     62                 else
     63                 {
     64                     return Nullable.GetUnderlyingType(t);
     65                 }
     66             }
     67             else
     68             {
     69                 return t;
     70             }
     71         }
     72 
     73         //*************************************************
     74         /// <summary>
     75         /// List转Datatable
     76         /// </summary>
     77         /// <typeparam name="T"></typeparam>
     78         /// <param name="table"></param>
     79         /// <returns></returns>
     80         public static IList<T> ConvertTo<T>(DataTable table)
     81         {
     82             if (table == null)
     83             {
     84                 return null;
     85             }
     86 
     87             List<DataRow> rows = new List<DataRow>();
     88 
     89             foreach (DataRow row in table.Rows)
     90             {
     91                 rows.Add(row);
     92             }
     93 
     94             return ConvertTo<T>(rows);
     95         }
     96 
     97         public static IList<T> ConvertTo<T>(IList<DataRow> rows)
     98         {
     99             IList<T> list = null;
    100 
    101             if (rows != null)
    102             {
    103                 list = new List<T>();
    104 
    105                 foreach (DataRow row in rows)
    106                 {
    107                     T item = CreateItem<T>(row);
    108                     list.Add(item);
    109                 }
    110             }
    111 
    112             return list;
    113         }
    114 
    115         public static T CreateItem<T>(DataRow row)
    116         {
    117             T obj = default(T);
    118             if (row != null)
    119             {
    120                 obj = Activator.CreateInstance<T>();
    121 
    122                 foreach (DataColumn column in row.Table.Columns)
    123                 {
    124                     PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
    125                     try
    126                     {
    127                         object value = row[column.ColumnName];
    128                         prop.SetValue(obj, value, null);
    129                     }
    130                     catch
    131                     {  //You can log something here     
    132                        //throw;    
    133                     }
    134                 }
    135             }
    136 
    137             return obj;
    138         }
    139     }
    140 }

     

      DatatableToListHelper.cs中的内容为:

     1 using NPOI.SS.Formula.Functions;
     2 using System;
     3 using System.Collections.Generic;
     4 using System.Data;
     5 using System.Linq;
     6 using System.Reflection;
     7 using System.Text;
     8 using System.Threading.Tasks;
     9 using static ListToDatatable.Form1;
    10 
    11 namespace ListToDatatable
    12 {
    13     class DatatableToListHelper
    14     {
    15         /// <summary>  
    16         /// 利用反射和泛型  
    17         /// </summary>  
    18         /// <param name="dt"></param>  
    19         /// <returns></returns>  
    20         public static List<students> ConvertToList(DataTable dt)
    21         {
    22             // 定义集合  
    23             List<students> ts = new List<students>();
    24 
    25             // 获得此模型的类型  
    26             Type type = typeof(students);
    27             //定义一个临时变量  
    28             string tempName = string.Empty;
    29             //遍历DataTable中所有的数据行  
    30             foreach (DataRow dr in dt.Rows)
    31             {
    32                 students t = new students();
    33                 // 获得此模型的公共属性  
    34                 PropertyInfo[] propertys = t.GetType().GetProperties();
    35                 //遍历该对象的所有属性  
    36                 foreach (PropertyInfo pi in propertys)
    37                 {
    38                     tempName = pi.Name;//将属性名称赋值给临时变量  
    39                     //检查DataTable是否包含此列(列名==对象的属性名)    
    40                     if (dt.Columns.Contains(tempName))
    41                     {
    42                         // 判断此属性是否有Setter  
    43                         if (!pi.CanWrite) continue;//该属性不可写,直接跳出  
    44                         //取值  
    45                         object value = dr[tempName];
    46                         //如果非空,则赋给对象的属性  
    47                         if (value != DBNull.Value)
    48                             pi.SetValue(t, value, null);
    49                     }
    50                 }
    51                 //对象添加到泛型集合中  
    52                 ts.Add(t);
    53             }
    54             return ts;
    55         }
    56     }
    57 }

      OK,这是引用类型的list转datatable,完毕。

     

  • 相关阅读:
    数组和字符串//反转字符串
    数组和字符串//实现strStr()
    数组和字符串//二进制求和
    数组和字符串//加一
    数组和字符串//至少是其他数字两倍的最大数
    LeetCode111_求二叉树最小深度(二叉树问题)
    数据结构6.8_树的计数
    数据结构6.7_回溯法和树的遍历
    数据结构6.6_赫夫曼树及其应用
    数据结构6.5_树与等价问题
  • 原文地址:https://www.cnblogs.com/peng0731/p/7358351.html
Copyright © 2020-2023  润新知