类:
public class ModelConvertHelper<T> where T : new() { public static List<T> ConvertToModel(DataTable dt) { List<T> ts = new List<T>();//定义集合 //Type type = typeof(T);//获得此模型的类型 foreach (DataRow dr in dt.Rows) { T t = new T(); PropertyInfo[] propertys = t.GetType().GetProperties();//获取此模型的公共属性 foreach (PropertyInfo pi in propertys) { if (dt.Columns.Contains(pi.Name)) { if (!pi.CanRead) { continue; } object value = dr[pi.Name]; if (value != DBNull.Value) { pi.SetValue(t, value, null); } } } ts.Add(t); } return ts; } }
调用示例:
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { DataTable dt = new DataTable(); dt.Columns.Add(new System.Data.DataColumn("Code", typeof(string))); dt.Columns.Add(new System.Data.DataColumn("ChineseName", typeof(string))); dt.Columns.Add(new System.Data.DataColumn("UserApplicant", typeof(string))); dt.Columns.Add(new System.Data.DataColumn("Email", typeof(string))); dt.Columns.Add(new System.Data.DataColumn("CreateDate", typeof(string))); for (int i = 0; i < 100; i++) { DataRow dr = dt.NewRow(); dr[0] = "0801"; dr[1] = "赵孟蒙"; dr[2] = "mengmeng.zhao"; dr[3] = "xingkongmm@163.com"; dr[4] = DateTime.Now.ToString(); dt.Rows.Add(dr); } List<person> list = ModelConvertHelper<person>.ConvertToModel(dt); } } public class person { public string Code { get; set; } public string ChineseName { get; set; } public string UserApplicant { get; set; } public string Email { get; set; } public string CreateDate { get; set; } } }