Table、List互转

    public class ModelConvertHelper<T> where T:new ()
    {
        public static IList<T> ConvertToModel(DataTable dt)
        {
            IList<T> ts = new List<T>();
            Type type = typeof(T);
            PropertyInfo[] propertys = type.GetProperties();
            string tempName;
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;
                    if(dt.Columns.Contains(tempName))
                    {
                        if (!pi.CanWrite) continue;
                        object value = dr[tempName];
                        if (value != DBNull.Value) pi.SetValue(t,value,null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }
    }

 

        public static DataTable ListToTable(List<T> list)
        {
            Type type = typeof(T);
            PropertyInfo[] proInfos = type.GetProperties();
            DataTable dt = new DataTable();
            foreach (var p in proInfos)
            {
                dt.Columns.Add(p.Name, p.PropertyType);
            }
            foreach (var item in list)
            {
                DataRow dr = dt.NewRow();
                foreach (var p in proInfos)
                {
                    dr[p.Name] = p.GetValue(item);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

 

posted @ 2018-03-28 16:36  花生打代码会头痛  阅读(104)  评论(0)    收藏  举报