5

假设这是我的 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”)。谁能让我以正确的方式?

4

4 回答 4

10

甚至比 Yuck 的方法更短,并且不需要一次性将整个文件读入内存:)

var list = File.ReadLines(filename)
               .Where((ignored, index) => index % 2 == 1)
               .ToList();

诚然,它确实需要 .NET 4。关键部分是它的重载Where提供了索引以及谓词要作用的值。我们并不真正关心值(这就是我将参数命名为的原因ignored)——我们只需要奇数索引。显然,我们在构建列表时关心值,但这很好——它只被谓词忽略。

于 2012-08-01T16:48:19.433 回答
7

您可以将文件读取逻辑简化为一行,然后以这种方式遍历每一行:

var lines = File.ReadAllLines(myFile);
for (var i = 1; i < lines.Length; i += 2) {
  // do something
}

编辑:从你i = 1line2例子开始。

于 2012-08-01T16:45:55.657 回答
5

在循环内添加条件块和跟踪机制。(循环体如下:)

int linesProcessed = 0;
if( linesProcessed % 2 == 1 ){
  // Read the line.
  stdList.Add(line);
}
else{
  // Don't read the line (Do nothing.)
}
linesProcessed++;

该行linesProcessed % 2 == 1说:取我们已经处理过的行数,并找到mod 2这个数的。(将该整数除以 2 时的余数。)这将检查处理的行数是偶数还是奇数。

如果您没有处理任何行,它将被跳过(例如第 1 行,您的第一行。)如果您已经处理了一行或任何奇数行,请继续处理当前行(例如第 2 行。)

如果模块化数学给您带来任何麻烦,请参阅问题:https ://stackoverflow.com/a/90247/758446

于 2012-08-01T16:45:55.217 回答
0

试试这个:

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-01T16:46:52.287 回答