zoukankan      html  css  js  c++  java
  • datatable to list 方法转换

    #region 实体转换
    
            /// <summary>
            /// add extension method for datable
            /// </summary>
            /// <param name="dt"></param>
            /// <returns></returns>
            public static IList<TEntity> ToList<TEntity>(this DataTable dt) where TEntity : class ,new() {
                return ConvertToModel<TEntity>(dt);
            }
            public static IList<TEntity> ConvertToModel<TEntity>(DataTable dt) where TEntity : class ,new() {
                // 定义集合    
                IList<TEntity> ts = new List<TEntity>();
    
                // 获得此模型的类型   
                Type type = typeof(T);
                string tempName = "";
    
                foreach (DataRow dr in dt.Rows) {
                    TEntity t = new TEntity();
                    // 获得此模型的公共属性      
                    PropertyInfo[] propertys = t.GetType().GetProperties();
                    foreach (PropertyInfo pi in propertys) {
                        tempName = pi.Name;  // 检查DataTable是否包含此列    
    
                        if (dt.Columns.Contains(tempName)) {
                            // 判断此属性是否有Setter      
                            if (!pi.CanWrite) continue;
    
                            object value = dr[tempName];
                            if (value != DBNull.Value)
                                pi.SetValue(t, value, null);
                        }
                    }
                    ts.Add(t);
                }
                return ts;
            }
    
            #endregion
  • 相关阅读:
    【bzoj2242】[SDOI2011]计算器
    1109解题报告
    【bzoj3239】Discrete Logging
    【bzoj2480】Spoj3105 Mod
    【POJ1811】Prime Test
    【bzoj3667】Rabin-Miller算法
    【HDU2138】How many prime numbers
    卢卡斯定理
    线段树2
    畅快的甩卖
  • 原文地址:https://www.cnblogs.com/hualiu0/p/4587705.html
Copyright © 2011-2022 走看看