如何在C#中从SQL设置数据动态数组

时间:2018-12-11 08:53:24

标签: c# sql-server arraylist

如何在C#中从SQL Server设置数据。

我的班级学生:

public class student
{
    public int StudentID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

我想从SQL设置数据

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搜索结果,但未找到

1 个答案:

答案 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收藏集将吸引所有学生。