zoukankan      html  css  js  c++  java
  • DataTable和List互转

    /// <summary>
    /// list转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;
    }

    list转datatable

    public class DtToList<T> where T : new()
    {
    /// <summary>
    /// datatable转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;
    }
    }

    datatable转list

  • 相关阅读:
    寻找完全数(C++)
    莱布尼兹三角形(C++)
    简单的素数问题(C++)
    ubuntu17.04下安装LNMP
    ubuntu下连接mysql出现Access denied for user 'rose'@'localhost' (using password: NO)的解决方法
    快速理解面向对象的PHP编程--基础篇
    百度电面总结
    操作系统基础知识
    快速理解C语言指针
    新手学习MongoDB的基本命令
  • 原文地址:https://www.cnblogs.com/guzhengtao/p/20180828_1326.html
Copyright © 2011-2022 走看看