读取每个数字的字符串c#

dev*_*kkw 5 c# list

假设这是我的txt文件:

line1
line2
line3
line4
line5
Run Code Online (Sandbox Code Playgroud)

即时通讯阅读此文件的内容:

 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
}
Run Code Online (Sandbox Code Playgroud)

现在我想读取stdList中的数据,但每2行只读取一次值(在这种情况下我要读取"line2"和"line4").谁能让我以正确的方式?

Jon*_*eet 10

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

var list = File.ReadLines(filename)
               .Where((ignored, index) => index % 2 == 1)
               .ToList();
Run Code Online (Sandbox Code Playgroud)

不可否认,它确实需要.NET 4.关键部分是重载Where提供索引以及谓词作用的值.我们并不真正关心价值(这就是为什么我已经命名参数ignored) - 我们只想要奇数索引.显然我们关心构建列表时的值,但这很好 - 它只会被谓词忽略.


Yuc*_*uck 7

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

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

编辑:始于i = 1这是line2在你的榜样.

  • 它取决于 - "ReadAllLines"有大文件的问题,它将整个文件存储在内存中.`ReadLine()`是懒惰的,可以(理论上)处理任何大小的文件...... (2认同)
  • @Yuck:是的,但你真的不需要*明确地循环...看我的答案:) (2认同)

Bla*_*ble 5

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

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

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

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

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

  • +1因为它不需要您首先将整个文件读入字符串. (2认同)

Phi*_*idt 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
{
}
Run Code Online (Sandbox Code Playgroud)