Datatable 转换为List数组

Datatable 转换为List数组,闲话不多说,直接上代码:

 public List TableToList(DataTable dt, bool isStoreDB = true)
        {
            List list = new List();
            Type type = typeof(T);
            List listColums = new List();
            foreach (DataRow row in dt.Rows)
            {
                PropertyInfo[] pArray = type.GetProperties(); //集合属性数组  
                T entity = Activator.CreateInstance(); //新建对象实例  
                foreach (PropertyInfo p in pArray)
                {
                    if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value)
                    {
                        continue;  //DataTable列中不存在集合属性或者字段内容为空则,跳出循环,进行下个循环  
                    }
                    if (isStoreDB && p.PropertyType == typeof(DateTime) && Convert.ToDateTime(row[p.Name]) < Convert.ToDateTime("1753-01-01"))
                    {
                        continue;
                    }
                    try
                    {
                        var obj = Convert.ChangeType(row[p.Name], p.PropertyType);//类型强转,将table字段类型转为集合字段类型  
                        p.SetValue(entity, obj, null);
                    }
                    catch (Exception)
                    {
                        // throw;  
                    }
                }
                list.Add(entity);
            }
            return list;
        }


你可能感兴趣的:(C#,asp.net)