List与DataTable转换

 public class Total{

public  DataTable ListToDataTable<T>(IEnumerable<T> collection, DataTable dt)
        {
            var props = typeof(T).GetProperties();
            dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
            if (collection.Count() > 0)
            {
                for (int i = 0; i < collection.Count(); i++)
                {

                    ArrayList tempList = new ArrayList();

                    foreach (PropertyInfo pi in props)
                    {

                        object obj = pi.GetValue(collection.ElementAt(i), null);

                        tempList.Add(obj);

                    }
                    object[] array = tempList.ToArray();

                    dt.LoadDataRow(array, true);
                }
            }
            return dt;
        }
        public class ModelConvertHelper<T> where T : new()
        {
            public  List<T> ConvertToModel(DataTable dt)
            {
                Type type = typeof(T);  // 获得此模型的类型  
                string tempName = "";
                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)
                    {
                        tempName = pi.Name;  // 检查DataTable是否包含此列   
                        if (dt.Columns.Contains(tempName))
                        {
                            if (!pi.CanWrite) continue;// 判断此属性是否有Setter
                            object value = dr[tempName];
                            if (value != DBNull.Value)
                                pi.SetValue(t, value, null);
                        }
                    }
                    ts.Add(t);
                }
                return ts;
            }
        }

}

调用:public actionresult test(){

Total total=new Total();

iss = db.dbIssuseBackup.ToList();//连接数据库得到List集合

DataTable dt = new DataTable();

  total.ListToDataTable(iss, dt);//list转化为Datatable

  //dt.Columns.Remove("ID"); dt.Columns.Remove("SaveTime");//可以将dt某栏位移除

 Total.ModelConvertHelper<IssueLogBackup> aaaf = new Total.ModelConvertHelper<IssueLogBackup>();//datatable转化为List
            aaaf.ConvertToModel(dt);//IssueLogBackup为想要的Model

}

猜你喜欢

转载自blog.csdn.net/ai_feng123/article/details/81097270