【问题标题】:Fastest way to convert string array into object将字符串数组转换为对象的最快方法
【发布时间】:2015-10-29 16:25:49
【问题描述】:

我有一个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 有数百万学生,所以这必须尽可能快。我目前正在关注this sample,它从 CSV 文件中获取数据,但速度太慢 - 需要几分钟来转换和解析字符串。如何以最快的方式转换我的列表?

【问题讨论】:

  • 然后使 List 将其更改为 var lstObject = new List<Student>() 然后列表可以包含不同的数据类型..
  • .NET 有很多反序列化机制,尝试一些,看看哪个对你的用例来说是最快的。

标签: c# .net type-conversion


【解决方案1】:

您可以为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]);
}

但是,我认为您应该在这种情况下真正研究序列化。

【讨论】:

    【解决方案2】:

    new Student 添加到pre-allocated list 的常规循环会非常快:

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

    【讨论】:

      【解决方案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])
         });
      }
      

      【讨论】:

      • 感谢您的解决方案。我不敢相信我忽略了这么简单的事情。
      猜你喜欢
      • 2021-02-17
      • 2012-03-20
      • 1970-01-01
      • 2014-03-01
      • 2016-05-20
      • 2016-06-06
      • 2014-06-08
      • 1970-01-01
      • 2011-03-29
      相关资源
      最近更新 更多