DataTable 转换为List

       注意table 列的参数类型,若不为string 需要详细声明 如 typeof(Int32) 
        public static IList<T> ConvertTo<T>(DataTable dt) where T : new()
        {
            IList<T> list = new List<T>();
            if (dt == null || dt.Rows.Count <= 0)
            {
                return null;
            }  
            Type type = typeof(T);
            PropertyInfo[] propertys = type.GetProperties();//获取T的所有属性
            try
            {
                foreach (DataRow dr in dt.Rows)
                {
                    T t = new T();
                    foreach (PropertyInfo pi in propertys)
                    {  
                        if (dt.Columns.Contains(pi.Name))
                        {    
                            if (!pi.CanWrite) continue;
                            object value = dr[pi.Name];
                            if (value != DBNull.Value)
                                pi.SetValue(t, value, null);
                        }
                    }
                    list.Add(t);
                }
            }
            catch (Exception ex)
            {
                list = null;
            }
            return list;
        }

猜你喜欢

转载自www.cnblogs.com/cherious/p/11061973.html