流读取文本文件并从行中获取数据,并使用数据设置对象属性 [英] streamreading text file and getting data from lines and set objects properties with data

查看:112
本文介绍了流读取文本文件并从行中获取数据,并使用数据设置对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取流的流文本文件,但是代码无法有效工作.例如,文本文件的最大1000行,但是读取和写入数据到数据库大约需要几分钟...
在我的项目中,此后我逐行读取文本文件,我将这些行添加到字符串arrayList中.阅读完行后,将行设置为用于将数据写入数据库的对象.
这是我的文本阅读代码块;

List< string> dataList = new List< string>();
使用(StreamReader sr = new StreamReader(file))
{
字符串行;
while((line = sr.ReadLine())!= null)
{
如果(!string.IsNullOrEmpty(line))
dataList.Add(line);
}
}


我可以使我的代码更快吗?
而我的代码第二部分是,这需要更多时间;



BankObject headerObj =新的BankObject();

for(int i = 0; i

I''m streaming text files with stream read, But the code is not working efficiently. for example text file has max. 1000 lines but reading and writing data to db is takes about minutes...
In my project I''m reading text files line by line after that ,I''m adding this lines to a string arrayList. when I finish reading lines, I set lines to an object for writing data to my database.
This is my text reading code block;

List<string> dataList = new List<string>();
using (StreamReader sr = new StreamReader(file))
{
String line;
while ((line = sr.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line))
dataList.Add(line);
}
}


Can I make my codes faster?
And my codes second part is that takes more time ;



BankObject headerObj = new BankObject();

for (int i = 0; i

推荐答案

由于您显示的代码似乎只将dataList用作数组,所以为什么不直接使用
Since the code you show only appears to use dataList as an array, why not just use
string[] dataList = File.ReadAllLines(file);

而不是第一个循环-会更快.

您的第二个循环更难优化-它在一定程度上取决于数据的实际外观.我确实注意到,尽管您根本不检查以确保字符串中有足够的空间来提取子字符串-如果文件中的行是20个字符,会发生什么?使用foreach循环而不是for循环可能是值得的,因为它每次都会摆脱对数组的访问(尽管非调试构建无论如何都会对此进行优化).

除非必须,否则不要使用幻数-它们是维护的噩梦!

instead of your first loop - it will be much faster.

Your second loop is harder to optimize - it depends on what the data actually looks like to an extent. I do notice though that you don''t check at all to ensure there is enough room in the string to extract a substring - what happens if the line from the file is 20 characters? It may be worth using a foreach loop rather than the for loop as it would get rid of the array access each time (although the non-debug build would optimize this anyway).

Don''t use magic numbers unless you have to - they are a maintenance nightmare!


这篇关于流读取文本文件并从行中获取数据,并使用数据设置对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆