我的班级学生:
public class student
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * From Student";
cmd.Connection = con;
DataTable datatable = new DataTable();
con.Open();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
sqlDataAdapter.Fill(datatable);
con.Close();
sqlDataAdapter.Dispose();
foreach (DataRow dr in datatable.Rows)
{
//Set Data: ex: student[] students=new student[];
//students=new students{StudentID=dr["ID"],FirstName=dr["FirstName"]}
// ...
}
namespace WebApi2.myapi
{
public class StudentController : ApiController
{
student[] students = new student[]
{
new student { StudentID = 1, FirstName = "Jishan", LastName = "Siddique" },
new student { StudentID = 2, FirstName = "Bharat", LastName = "Darji" },
new student { StudentID = 3, FirstName = "Ravi", LastName = "Mori" },
new student { StudentID = 4, FirstName = "Jay", LastName = "Singh" }
};
public IEnumerable<student> GetStudents()
{
return students;
}
}
}
最后:我想要1个类似的结果:student.StudentID = dr [“ ID”]; student.FirstName = dr [“ FirstName”]
谢谢大家的观看。对不起,我的英语不好。
我在Google搜索结果,但未找到
答案 0 :(得分:3)
您可以通过从DataRow
获取价值来实现:
List<student> students = new List<student>();
foreach (DataRow dataRow in datatable.Rows)
{
students.Add(new student(){
StudentID =dataRow["StudentID"];
FirstName = dataRow["FirstName"] ;
LastName = dataRow["LastName"] ;
})
}
因此,students
收藏集将吸引所有学生。