Reading a line each C # number

suppose this is my txt file:

line1
line2
line3
line4
line5

im reading the contents of this file using

 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
}

Now I want to read the data in stdList, but only read the value every two lines (in this case I have to read the lines "line2" and "line4"). can anyone put me on the right track?

+5
source share
4 answers

try the following:

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
{
}
0
source

Even shorter than Yuck, and he doesn’t need to read the whole file in memory at a time :)

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

, .NET 4. Where, , . ( ignored) - . , , , - .

+10

:

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

EDIT: i = 1, line2 .

+7

. ( :)

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

The line linesProcessed % 2 == 1says: take the number of lines that we have already processed and find mod 2this number. (The rest, when you divide this integer by 2.) This will check whether the number of processed rows is even or odd.

If you have not processed any lines, this will be skipped (for example, line 1, your first line.) If you have already processed one line or any odd number of lines, continue and process this current line (for example, line 2.)

If modular math gives you any problems, see the question: fooobar.com/questions/36269 / ...

+5
source

All Articles