/// <summary> /// 1step:定义实体类 /// </summary> class PhoneNum { int pId; public int PId { get { return pId; } set { pId = value; } } int pTypeId; public int PTypeId { get { return pTypeId; } set { pTypeId = value; } } string pName; public string PName { get { return pName; } set { pName = value; } } string pCellPhone; public string PCellPhone { get { return pCellPhone; } set { pCellPhone = value; } } string pHomePhone; public string PHomePhone { get { return pHomePhone; } set { pHomePhone = value; } } }
/// <summary> /// 2step:定义转化的方法 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static List<PhoneNum> GetPNList(DataTable dt) //定义静态方法,传递DataTable参数 { List<PhoneNum> pnlist = null; //定义一个list<实体类>集合为空 if (dt.Rows.Count > 0) //判断获得的DataTable是否有数据,如果有,则实例化List<>集合,否则返回空集合 { pnlist = new List<PhoneNum>(); } else { return pnlist; } foreach (DataRow item in dt.Rows) // 遍历DataTable中的行 { PhoneNum temp = new PhoneNum(); //将实体类实例化 temp.PId = (int)item["pid"]; //将DataTable行中的对应字段数据赋值给实体属性 temp.PTypeId = (int)item["ptypeid"]; temp.PName = item["pname"].ToString(); temp.PCellPhone = item["pcellphone"].ToString(); temp.PHomePhone = item["phomephone"].ToString(); pnlist.Add(temp); //List<>集合添加赋值后的行 } return pnlist; //返回赋值后的List<>集合 }