代码段——List<T>与DataTable互转

        public static DataTable ListToDataTable<T>(List<T> entitys)
        {
            //获取T对象的所有公共属性
            PropertyInfo[] entityProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            //创建DataTable,T类型名称作为Datatable name
            DataTable dt = new DataTable(typeof(T).Name);
            //为DataTable添加列
            for (int i = 0; i < entityProperties.Length; i++)
            {
                dt.Columns.Add(entityProperties[i].Name);
            }
            //将所有entity添加到DataTable中
            foreach (T entity in entitys)
            {
                object[] entityValues = new object[entityProperties.Length];
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    entityValues[i] = entityProperties[i].GetValue(entity, null);
                }
                dt.Rows.Add(entityValues);
            }
            return dt;
        }

        public static List<T> DatatableToList<T>(DataTable dt) where T : new()
        {
            List<T> ts = new List<T>();
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                // 获得此模型的公共属性
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    //判断Datatable中是否包含此列
                    if (dt.Columns.Contains(pi.Name))
                    {
                        // 判断此属性是否有Setter
                        if (!pi.CanWrite)
                        {
                            continue;
                        }
                        object value = dr[pi.Name];
                        if (value != DBNull.Value)
                        {
                            pi.SetValue(t, value, null);
                        }
                    }
                }
                ts.Add(t);
            }
            return ts;
        }
posted @ 2023-02-22 17:19  shanzm  阅读(66)  评论(0编辑  收藏  举报
TOP