跳过读取特定行数(使用StreamReader) [英] Skip Reading Specific Number Of Lines (Using StreamReader)

查看:731
本文介绍了跳过读取特定行数(使用StreamReader)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




所以我想做的是在使用流阅读器阅读文本文件时跳过读取特定行数。



这个代码我想尝试做的是加载文本文件并跳过特定数量的行并将其加载到列表框中。



到目前为止我有这个代码



Hi
So what i am trying to do is to skip reading a specific number of lines when reading a textfile using stream reader.

This code i want to try an do is to load a text file and skip a specific number of lines and load it in a list box.

I have this code so far

string[] allines = File.ReadLines(@"Root").Skip(3)

listbox.items.addrange(alllines);









但是当将文本文件加载到列表框中时,跳过位不起作用,因为行仍然出现在列表框中。



任何建议和帮助请:)





but the skip bit does not work when loading the text file into a listbox as the lines still come up in the list box.

any suggestions and help please :)

推荐答案

你没有任何代码可以跳过任何行,所以它将所有行加载到ListBox中。



你必须逐个枚举行集合,并且只添加你想要的ListBox的行,取决于一些cond您没有指定。



一次加载一行的另一个好处是,您不会破坏内存将整个文件加载到数组,如果源文件很大。
You don''t have any code in there to skip any lines, so it''s loading all the lines into the ListBox.

You have to enumerate the collection of lines, one-by-one, and only add the lines to the ListBox that you want, depending on some condition you didn''t specify.

The other benefit of loading one line at a time is that you''re not crushing your memory loading an entire file into an array if the source file is huge.


你的问题,我相信Skip使用deferred执行的事实。



(见以下链接的评论)

http ://msdn.microsoft.com/en-us/library/bb358985(v = vs.90).aspx [ ^ ]



我建议打破代码有点下降:



Your issue, I believe relates to the fact that Skip uses defered execution.

(see remarks on the following link)
http://msdn.microsoft.com/en-us/library/bb358985(v=vs.90).aspx[^]

I would suggest breaking the code down a bit:

IEnumerable<string> allines = File.ReadLines(@"Root");
IEnumerable<string> cutDown = alllines.Skip(3).GetEnumerator();
listbox.items.addrange(alllines);





或者你可以这样做:





Or you could do:

IEnumerable<string> allines = File.ReadLines(@"Root");
IEnumerable<string> cutDown = alllines.Skip(3);

foreach( string s in cutDown)
{
    listbox.items.add(s);
}


我会添加正确的解决方案1:跳过一行意味着阅读它。在这种情况下,这与线条具有不同长度的简单事实有关。在您访问某些行之前,您必须阅读所有之前的行;在你这样做之前,你真的不知道下一行的位置。



你只需要逐行读取行,忽略其中一些行。 ReadToEnd System.IO.File.ReadAllLines 等方法可能适合也可能不适合;如果文件太大,则不适合。



-SA
I would add to the correct Solution 1: "skipping" a line means reading it. In this case, this is related to the simple fact that the lines have different length. Before you can access some line, you have to read all the previous lines; before you do it, you cannot really know the position of the next line.

You just need to read lines one by one ignoring some of them. The methods like ReadToEnd or System.IO.File.ReadAllLines may or may not be suitable; not suitable if the file is too big.

—SA


这篇关于跳过读取特定行数(使用StreamReader)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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