using System; using System.Data; class DataTableObjectConversion { class Person { public string Name { get; set; } public int Age { get; set; } } // DataTable 转对象类 public static List<Person> DataTableToObject(DataTable dt) { List<Person> persons = new List<Person>(); foreach (DataRow row in dt.Rows) { Person person = new Person { Name = row["Name"].ToString(), Age = Convert.ToInt32(row["Age"]) }; persons.Add(person); } return persons; } // 对象类转 DataTable public static DataTable ObjectToDataTable(List<Person> persons) { DataTable dt = new DataTable(); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Age", typeof(int)); foreach (var person in persons) { dt.Rows.Add(person.Name, person.Age); } return dt; } }
推荐阅读