利用泛型实现DataTable转List通用类

46
补充展位 Pages_Weblog_Get#0
文章摘要
此内容由人工摘要内容,并由AI根据文章内容进行润色
暂无内容

随着通用形式的ORM迭代升级越来越方便 本文提供的利用泛型实现DataTable转List通用类代码 实际上可用价值已经很低了,留在这里单纯作为笔记记录下

/// <summary>
/// 根据实体属性自动序列化
/// </summary>
/// <typeparam name="T">数据泛类型</typeparam>
/// <param name="dt">datatable</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dt) where T : new()
{
            if (dt == null)
            {
                return new List<T>();
            }

            Type type = typeof(T);
            List<T> list = new List<T>();
            string tempName = string.Empty;
            foreach (DataRow row in dt.Rows)
            {
                PropertyInfo[] pArray = type.GetProperties();
                T entity = new T();
                foreach (PropertyInfo p in pArray)
                {
                  
                        tempName = p.Name;
                        if (!p.CanWrite) continue;
                        object value = row[tempName];
                        if (value != DBNull.Value) p.SetValue(entity, value, null);
                    
                }
                list.Add(entity);
     }
      return list;
}
补充展位
Pages_Weblog_Get#706d5273-66b7-4d42-b2fe-cdb0a12fab53
补充展位 Pages_Weblog_Get#1
补充展位 Pages_Weblog_Get#2
专题推荐
暂无内容
补充展位 Pages_Weblog_Get#3