将文本文件读入自定义数据类
我有一个文本文件,其中包含整数、双精度或字符串数据列。我想将每一行数据读入我自己的记录类中。我事先知道列数据类型,所以我正在解析一个文本文件行,类似于下面的代码(我输入了它,所以不要抱怨有错误)。我没有列出所有列,因此 switch 语句将有 74 种情况。我不知道这是否是最好的方法。有什么更好的方法来做到这一点?此外,它需要尽可能快。
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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您真的需要那个
开关
吗?怎么样:Do you really needs that
switch
? What about: