开发者

read text file into custom data class

开发者 https://www.devze.com 2022-12-16 03:28 出处:网络
I have a text file which contains columns of data that are either integer, double or string.I want to read each row of data into my own record class.I开发者_如何学编程 know the column data types befor

I have a text file which contains columns of data that are either integer, double or string. I want to read each row of data into my own record class. I开发者_如何学编程 know the column data types beforehand, so I am parsing a text file row something like the code below (I typed it out, so don't complain there are errors). I didn't list all of the columns, so the switch statement would have 74 cases. I don't know if this the best way to go about it. What is a better way to do this? Also, it needs to be fast as possible.

List<record> records = new List<record>();

string[] split = textRow.Split(new string { "," }, StringSplitOptions.None);
record = new Record();
for (int i=0;i<split.Length;i++)
{      
   switch (i)
   {
      case 0: 
         record.ID = Convert.ToInt32(split[0]);
         break;
      case 1:
         record.Name = split[1];
         break;
      case 2:
         record.Rate = Convert.ToDouble(split[2]);
         break;
      case 3:
         record.Price = Convert.ToDouble(split[3]);
         break;
      case 4:
         record.Rank = Convert.ToInt32(split[4]);
         break;

   }
}

records.Add(record);


Do you really needs that switch? What about:

string[] split = textRow.Split(new string { "," }, StringSplitOptions.None);
record = new Record();
record.ID = Convert.ToInt32(split[0]);
record.Name = split[1];
record.Rate = Convert.ToDouble(split[2]);
record.Price = Convert.ToDouble(split[3]);
record.Rank = Convert.ToInt32(split[4]);
0

精彩评论

暂无评论...
验证码 换一张
取 消