datatable to object array
-
I have a table that would be read into the dataset using dataadapter.fill method. The table will be of the below format Name | Age | Score | Gender Ram 14 75 M Sam 15 85 M John 16 95 M I have an object of the following sort in c# public class students { //initializing private variables public string Name { //get/set } public string Age { //get/set } public string Score { //get/set } } How can i convert this table in the dataset to an array of Students object?
Jack Sparrow -------------------------------------- Defeat is not the worst of failures. Not to have tried is the true failure.
-
I have a table that would be read into the dataset using dataadapter.fill method. The table will be of the below format Name | Age | Score | Gender Ram 14 75 M Sam 15 85 M John 16 95 M I have an object of the following sort in c# public class students { //initializing private variables public string Name { //get/set } public string Age { //get/set } public string Score { //get/set } } How can i convert this table in the dataset to an array of Students object?
Jack Sparrow -------------------------------------- Defeat is not the worst of failures. Not to have tried is the true failure.
There are many ways. You might encapsulate Data objects within your classes, and maybe getting a IEnumerable<Student> could be a better approach:
public class Student
{
DataRow dr;internal Student(DataRow dr) { this.dr = dr; } public string Name { get { return dr\["Name"\].ToString(); } set { dr\["Name"\] = value; } } public string Age { get { return dr\["Age"\].ToString(); } set { dr\["Age"\] = value; } } public string Score { get { return dr\["Score"\].ToString(); } set { dr\["Score"\] = value; } } // And more properties as needed
}
public class StudentCollection
{
public IEnumerable<Student> GetStudents()
{
// Once you've got the DataTable, called "dt" for example
foreach (DataRow dr in dt.Rows)
yield return new Student(dr);
}
}modified on Wednesday, December 15, 2010 11:35 AM
-
I have a table that would be read into the dataset using dataadapter.fill method. The table will be of the below format Name | Age | Score | Gender Ram 14 75 M Sam 15 85 M John 16 95 M I have an object of the following sort in c# public class students { //initializing private variables public string Name { //get/set } public string Age { //get/set } public string Score { //get/set } } How can i convert this table in the dataset to an array of Students object?
Jack Sparrow -------------------------------------- Defeat is not the worst of failures. Not to have tried is the true failure.
If you want the data in an array of some class why bother reading it into a DataTable? That just wastes cycles. Cut out the middleman; use a DataReader to populate your array.