将文本文件读入自定义数据类

发布于 2024-08-17 02:06:17 字数 838 浏览 8 评论 0原文

我有一个文本文件,其中包含整数、双精度或字符串数​​据列。我想将每一行数据读入我自己的记录类中。我事先知道列数据类型,所以我正在解析一个文本文件行,类似于下面的代码(我输入了它,所以不要抱怨有错误)。我没有列出所有列,因此 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寻找一个思念的角度 2024-08-24 02:06:17

您真的需要那个开关吗?怎么样:

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]);

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]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文