zoukankan      html  css  js  c++  java
  • C# DataTable转List<Model>通用类

    /// <summary>
    /// DataTable转换为List&lt;Model&gt;
    /// </summary>
    public static class DataTableToListModel<T> where T : new()
    {
        public static IList<T> ConvertToModel(DataTable dt)
        {
            //定义集合
            IList<T> ts = new List<T>();
            T t = new T();
            string tempName = "";
            //获取此模型的公共属性
            PropertyInfo[] propertys = t.GetType().GetProperties();
             foreach (DataRow row in dt.Rows)
            {         
                t = new T();
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;
                    //检查DataTable是否包含此列
                    if (dt.Columns.Contains(tempName))
                    {
                        //判断此属性是否有set
                        if (!pi.CanWrite)
                            continue;
                        object value = row[tempName];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }
    }
  • 相关阅读:
    致虚极守静笃
    DNS 透明代理
    Java“禁止”泛型数组
    Java和C#语法对比
    JVM 内存区域 (运行时数据区域)
    Java8 使用
    G1收集器的收集原理
    BZOJ 2222: [Cqoi2006]猜数游戏【神奇的做法,傻逼题,猜结论】
    数据结构之网络流入门(Network Flow)简单小节
    BZOJ 1257: [CQOI2007]余数之和sum【神奇的做法,思维题】
  • 原文地址:https://www.cnblogs.com/sydeveloper/p/3044369.html
Copyright © 2011-2022 走看看