Reputation: 139
I have a List<string[]> stringStudentList
where for each student array contains strings of all the properties. I need to convert this into the object Student in the fastest way possible.
For example string[] student1 = {"Billy", "16", "3.32", "TRUE");
needs to be converted to the class:
class Student
{
string name { get; set; }
int age { get; set; }
double gpa { get; set; }
bool inHonors { get; set; }
}
Then inserted into a List<Student>
. There are millions of students in stringStudentList
so this has to be as fast as possible. I am currently following this sample which grabs data from a CSV file but it is much too slow - takes several minutes to convert & parse the strings. How do I convert my list in the fastest way possible?
Upvotes: 0
Views: 12892
Reputation: 100527
Regular loop adding new Student
into pre-allocated list would be quite fast:
//List<string[]> stringStudentList
var destination = new List<Student>(stringStudentList.Length);
foreach(var r in stringStudentList)
{
destination.Add(new Student
{
name =r[0],
age = int.Parse(r[1]),
gpa = double.Parse(r[2]),
inHonors = r[3] == "TRUE"
});
}
Upvotes: 4
Reputation: 1435
You can create a constructor for Student
that takes a string[]
as an argument:
Student(string[] profile)
{
this.name = profile[0];
this.age = int.Parse(profile[1]);
this.gpa = double.Parse(profile[2]);
this.inHonor = bool.Parse(profile[3]);
}
However, I think you should really look into Serialization in a situation like this.
Upvotes: 5
Reputation: 1800
Something like this should work
var list students = new List<Student>();
foreach(var student in stringStudentList)
{
students.Add(new Student
{
name = student[0]
age = int.Parse(student[1]),
gpa = double.Parse(student[2]),
inHonors = bool.Parse(student[3])
});
}
Upvotes: 1