views:

58

answers:

1

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);
+3  A: 

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]);
Rubens Farias
Your right! I don't know what I was thinking. <- feels dumb now.
John Sheares
If you're working on that on Sunday, I can understand it =)
Rubens Farias