Skip to main content
 首页 » 编程设计

c#之读取特定行之间的一行

2024年02月06日10JustinYoung

我有一个这样结构的文本文件(文件的一部分):

          B                            NO        AMOUNT 
            W                          10        200.00 
            R                           1        110.00 
            TOTAL                      11         90.00 
                    111 TOTALS 
          A                            NO        AMOUNT 
            W                       4,159        640.00 
            R                           0         00.00 
            TOTAL                   4,159        640.00 
 
          B                            NO        AMOUNT 
            W                          10        200.00 
            R                           1        110.00 
            TOTAL                      11         90.00 
 
                    222  TOTALS 
          A                            NO        AMOUNT 
            W                       4,000        510.00 
            R                           0         10.00 
            TOTAL                   4,000        500.00 

我需要阅读以“TOTAL”开头的行在“111 TOTALS”和“222 TOTALS”行之间。

我有以下代码来读取以“TOTAL”开头的行,我只是不知道如何/在代码中的何处可以包含此“介于”条件:

using System; 
using System.IO; 
 
public class TextFile4 
{ 
  public static void ReadTextFile4() 
  { 
    int counter = 0; 
    string line; 
 
    //Find application path 
    string dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); 
 
    //Name of the file 
    string filepath = dir + @"\Reports\abc.txt"; 
 
    // Read the file and display it line by line 
    StreamReader file = new StreamReader(filepath); 
 
    // Loop through text file 
    while ((line = file.ReadLine()) != null) 
    { 
        if (line.Trim().StartsWith("TOTAL")) 
        { 
            Console.WriteLine(line); 
        } 
    counter++; 
    } 
    file.Close(); 
  } 
} 

可能是搜错了,没找到类似的话题。看到一些关于计算行数的话题,但它是这个文件中的一个变量,所以不是一个选项。

请您参考如下方法:

这是应该有效的强制性 LINQ 方法( 未测试 ):

string[] totalLines = File.ReadLines(filepath) 
    .SkipWhile(l => !l.TrimStart().StartsWith("111 TOTALS")) 
    .TakeWhile(l => !l.TrimStart().StartsWith("222  TOTALS")) 
    .Where(l => l.TrimStart().StartsWith("TOTAL")) 
    .ToArray(); 

结果:

        TOTAL                   4,159        640.00 
        TOTAL                      11         90.00