[英]Fastest way to convert string array into object
我有一個List<string[]> stringStudentList
,其中每個學生數組都包含所有屬性的字符串。 我需要以最快的方式將其轉換為對象Student。
例如string[] student1 = {"Billy", "16", "3.32", "TRUE");
需要轉換為該類:
class Student
{
string name { get; set; }
int age { get; set; }
double gpa { get; set; }
bool inHonors { get; set; }
}
然后插入List<Student>
。 stringStudentList
中有數百萬的學生,因此必須盡可能快。 我目前正在關注該示例 , 該示例從CSV文件中獲取數據,但是速度太慢-花費幾分鍾的時間來轉換和解析字符串。 如何以最快的方式轉換列表?
定期循環將new Student
添加到預先分配的列表中會非常快:
//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"
});
}
您可以為Student
創建一個構造函數,該構造函數將string[]
作為參數:
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]);
}
但是,我認為您應該在這種情況下真正研究序列化。
這樣的事情應該工作
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])
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.