C#DatatableToList

static void Main(string[] args)
{
   List<Student> student=new List<Student>();
   DataTable table=CreateTable();
   foreach(DataRow row in table.Rows)
   {
     Type type=Typeof(Student);
     Student stu=new Student();
     foreach(var item in type.GetProperties())
     {
       object obj=row[item.Name];
       item.SetValue(student,obj);
     }
     students.Add(student);
   }
   
}
public static DataTable CreateTable()
{
   //创建一个datatable
   DataTable table=new DataTable();
   //创建一个列对象
   DataColumn c1=new DataColumn("ID",typeof(int));
   //创建一个列对象
   DataColumn c1=new DataColumn("Name",typeof(string));
   table.Columnn.Add(c1);
   table.Columnn.Add(c2);
   for(int i=0;i<5;i++){
      DataRow row=table.NewRow();
      row["ID"]=i+1;
      row["Name"]="型"+i.ToStrinng();
      table.Rows.Add(row);
   }
   return table;
}

猜你喜欢

转载自blog.csdn.net/qq_40098572/article/details/84613190
C