假设这是我的txt文件:
line1
line2
line3
line4
line5我正在使用以下命令读取此文件的内容:
string line;
List<string> stdList = new List<string>();
StreamReader file = new StreamReader(myfile);
while ((line = file.ReadLine()) != null)
{
stdList.Add(line);
}
finally
{//need help here
}现在我想在stdList中读取数据,但是每2行只读一次值(在本例中,我必须读取"line2“和"line4")。有没有人能把我放在正确的位置?
发布于 2012-08-02 00:46:52
试试这个:
string line;
List<string> stdList = new List<string>();
StreamReader file = new StreamReader(myfile);
while ((line = file.ReadLine()) != null)
{
stdList.Add(line);
var trash = file.ReadLine(); //this advances to the next line, and doesn't do anything with the result
}
finally
{
}发布于 2012-08-02 00:48:19
甚至比Yuck的方法更短,而且它不需要一次性将整个文件读取到内存中:)
var list = File.ReadLines(filename)
.Where((ignored, index) => index % 2 == 1)
.ToList();诚然,它确实需要.NET 4。关键部分是overload of Where,它为谓词提供索引和值以供操作。我们并不真正关心这个值(这就是为什么我将这个参数命名为ignored) --我们只需要奇怪的索引。显然,当我们构建列表时,我们关心的是值,但这很好-它只在谓词中被忽略。
发布于 2012-08-02 00:45:56
您可以将文件读取逻辑简化为一行,然后以这种方式循环遍历每隔一行:
var lines = File.ReadAllLines(myFile);
for (var i = 1; i < lines.Length; i += 2) {
// do something
}编辑:从i = 1开始,在您的示例中是line2。
https://stackoverflow.com/questions/11763821
复制相似问题