zoukankan      html  css  js  c++  java
  • C# List和DataTable的相互转换

    1、List转DataTable

     /// <summary>
     /// list to datatable
     /// </summary>
     /// <typeparam name="T"></typeparam>
     /// <param name="collection"></param>
     /// <returns></returns>
     public  DataTable  ListToDt<T>(IEnumerable<T> collection)
     {
         var props = typeof(T).GetProperties();
         var dt = new DataTable();
         dt.Columns.AddRange(props.Select(p => new 
         DataColumn(p.Name, p.PropertyType)).ToArray());
         if (collection.Count() > 0)
         {
             for (int i = 0; i < collection.Count(); i++)
             {
                 ArrayList tempList = new ArrayList();
                 foreach (PropertyInfo pi in props)
                 {
                     object obj = pi.GetValue(collection.ElementAt(i), null);
                     tempList.Add(obj);
                 }
                 object[] array = tempList.ToArray();
                 dt.LoadDataRow(array, true);
              }
          }
          return dt;
     }

    2、DataTable转List

    public class DtToList<T> where T : new()  
    {
         /// <summary>
         /// datatable to list
         /// </summary>
         /// <param name="dt"></param>
         /// <returns></returns>
         public static  List<T> ConvertToModel(DataTable dt)
         {
    
             List<T> ts = new List<T>();// 定义集合
             Type type = typeof(T); // 获得此模型的类型
             string tempName = "";
             foreach (DataRow dr in dt.Rows)
             {
                 T t = new T();
                 PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                 foreach (PropertyInfo pi in propertys)
                 {
                     tempName = pi.Name;
                     if (dt.Columns.Contains(tempName))
                     {
                         if (!pi.CanWrite) continue;
                         object value = dr[tempName];
                         if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                     }
                 }
                 ts.Add(t);
             }
             return ts;
         }
    }
  • 相关阅读:
    静态变量一定要先声明后赋值
    建议3 三元操作的类型必一致
    IDEA 创建 Maven web项目注意事项
    js不同类型作比较
    exception中return方法
    exception 打印出异常栈踪迹
    spring controller使用了@ResponseBody却返回xml
    springboot中的406(Not Acceptable)错误
    把本地建好的项目提交到git上
    java基础---------方法和方法重载
  • 原文地址:https://www.cnblogs.com/ElvisZhongShao/p/11002006.html
Copyright © 2011-2022 走看看