读取文本文件跳过一堆行然后继续到其他行

时间:2015-05-11 11:35:17

标签: c# linq streamreader

我想跳过我将在文本文件中读取的行,如下图所示,第0行,第1行和第2行是跳过(文本文件的前三行),然后是读取此行(3读取)这个)接下来就是(4跳过这个)

这就是模式:

(跳过前3行文本文件,然后跳过 (3)然后读这个 (4)跳过  这直到文本文件结束)冲洗并重复其他文本文件,我需要这种模式的帮助。

Line 0 - Skip This
Line 1 - Skip This
Line 2 - Skip This
Line 3 - Read This
Line 4 - Read This
Line 5 - Read This
Line 6 - Skip This
Line 7 - Skip This
Line 8 - Skip This
Line 9 - Skip This
Line 10 - Read This
Line 11 - Read This
Line 12- Read This
Line 13 - Skip This
Line 14 - Skip This
Line 15- Skip This
Line 16- Skip This
Line 17 - Read This and so on

我试过的代码。

string[] Lines = File.ReadAllLines(f.File);
foreach (string line in Lines.Skip(3))
{
   try
   {
      string[] readLineSplit = line.Split('|');

      if (readLineSplit.Length > 1)
      {
         var id = readLineSplit[0].ToString();
         var flagvalue = readLineSplit[1].ToString();
         var status = readLineSplit[2].ToString();
         Lines.Skip(4).ToString();
         Console.WriteLine("ID {0}, Value {1}, Status {2}", id, flagvalue, status)
      }    
   }
   catch (FileNotFoundException error)
   {   
      Console.WriteLine(error);
   }
}

4 个答案:

答案 0 :(得分:3)

这有帮助吗?

string[] Lines = File.ReadAllLines(f.File);
for (int i = 3; i < Lines.Length-3; i += 7)
{
  for (int j = 0; j < 3; j++)
  {
    string[] readLineSplit = Line [i+j].Split('|');
    etc..
  }
}

答案 1 :(得分:3)

这将是一个简短的LINQ解决方案:

var result = Lines.Skip(3).Where((val,idx)=>idx%7<3).Select((x)=>x);

Lines可以是文件所有行的数组,也可以只是File.ReadLines(filename)

答案 2 :(得分:2)

不是读取所有行,然后尝试提取所需的行,而是只需读取所需的行而不将不需要的行存储在内存中:

var lines = new List<string>();
var counter = 0;
using (var sr = new StreamReader(filename)) {
    string line;
    while ((line = sr.ReadLine()) != null) {
        //ignore the first 3 lines
        if (counter >= 3) {
            //now work out where in the pattern of 7 (3 read, 4 skip) we are
            var mod = (counter - 3) % 7;
            //if the first 3 of the 7, keep it
            if (mod < 3)
                lines.Add(line);
        }
        counter++;
    }
}

答案 3 :(得分:1)

您最好使用流阅读器,但对于Linq,Skip / Take答案尝试

        List<string> lines = Enumerable.Range(0, 100).Select(i => i.ToString()).ToList();

        IEnumerable<string> group;
        int c = 0;
        do
        {
            group = lines.Skip(3+7*c).Take(3);
            foreach (var s in group)
            {
                Console.WriteLine(s);
            }
            c++;
        } while (group.Count() == 3);