c# datatable to list(datatable 转换为 list方法)

实体类定义

    /*
     定义一个实体类
     */

    public class tbBackEntity {
        public int keyId { get; set; }
        public string a { get; set; }
        public string b { get; set; }
    }


DataSet ds = db.ExecProcParameterReDataSet("pr_testTableType",p); DataTable tbBack = new DataTable(); if (ds.Tables.Count > 0) { tbBack = ds.Tables[0]; }


一、datatable 循环遍历生成一个新的实体

            //方法一
             List< tbBackEntity > t2= new List< tbBackEntity >(); 
            foreach (DataRow r in tbBack.Rows)
             {
                 t2.Add(new tbBackEntity { 
                  keyId = int.Parse(r["keyId"].ToString()),
                   a = r["a"].ToString(),
                   b = r["b"].ToString()
                 });
             }
 
   


二、通过linq方法生成一个新的list实体对象

     //方法二
           List< tbBackEntity >  t = tbBack.AsEnumerable().Select(
                 p1 => new tbBackEntity { 
                 keyId = p1.Field< int >("keyId"),
                 a = p1.Field< string >("a"),
                 b = p1.Field< string >("b")
                 }
                 ).ToList();