C# DataTable转List
ORM:
1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.Linq; 5 using System.Reflection; 6 using System.Web; 7 8 namespace WebApplication1.date 9 { 10 public class ORM 11 { 12 static public List<T> Tolist<T>(DataTable dt) where T : class, new() 13 { 14 Type t = typeof(T); 15 PropertyInfo[] PropertyInfo = t.GetProperties(); 16 List<T> list = new List<T>(); 17 18 string typeName = string.Empty; 19 foreach (DataRow item in dt.Rows) 20 { 21 T obj = new T(); 22 foreach (PropertyInfo s in PropertyInfo) 23 { 24 typeName = s.Name; 25 if (dt.Columns.Contains(typeName)) 26 { 27 if (!s.CanWrite) continue; 28 29 object value = item[typeName]; 30 if (value == DBNull.Value) continue; 31 32 if (s.PropertyType == typeof(string)) 33 { 34 s.SetValue(obj, value.ToString(), null); 35 } 36 else 37 { 38 s.SetValue(obj, value, null); 39 } 40 } 41 } 42 list.Add(obj); 43 } 44 return list; 45 } 46 47 } 48 }
创建DataTable:
1 DataTable tblDatas = new DataTable("User"); 2 DataColumn dc = null; 3 dc = tblDatas.Columns.Add("Id", Type.GetType("System.Int32")); 4 dc.AutoIncrement = true;//自动增加 5 dc.AutoIncrementSeed = 1;//起始为1 6 dc.AutoIncrementStep = 1;//步长为1 7 dc.AllowDBNull = false;// 8 9 dc = tblDatas.Columns.Add("Name", Type.GetType("System.String")); 10 dc = tblDatas.Columns.Add("Pwd", Type.GetType("System.String")); 11 12 DataRow newRow; 13 newRow = tblDatas.NewRow(); 14 newRow["Name"] = "张三"; 15 newRow["Pwd"] = "123"; 16 tblDatas.Rows.Add(newRow); 17 18 newRow = tblDatas.NewRow(); 19 newRow["Name"] = "李四"; 20 newRow["Pwd"] = "123456"; 21 tblDatas.Rows.Add(newRow); 22 //调用ORM TOlist 泛型 23 var i = ORM.Tolist<User>(tblDatas); 24 var a = JsonConvert.SerializeObject(i); 25 Console.WriteLine(a); 26 Console.ReadKey();
创建类 User
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 namespace ConsoleApp1 7 { 8 public class User 9 { 10 public int Id { get; set; } 11 public string Name { get; set; } 12 public string Pwd { get; set; } 13 } 14 }