0

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?

2
  • then make the List<string[]> change it to be var lstObject = new List<Student>() then the list can hold different datatypes..
    – MethodMan
    Oct 29, 2015 at 16:29
  • There are many deserialization mechanisms for .NET, try out a few and see which one's the fastest for your use case(s).
    – Chris O
    Oct 29, 2015 at 16:30

3 Answers 3

5

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.

3

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"
    });
}
0
1

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])
   });
}
1
  • Thanks for the solution..I can't believe I overlooked something so simple.
    – A C
    Oct 29, 2015 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.