使用LINQ处理文本文件

use*_*429 3 c# linq

文本文件格式

headerinfo = "abc"
**part1=001**
element1
element2....
...
element15
end_element
**part2=002**
element1
element2....
...
emelent15
end_element
......
end_header

我想从part1=001最多但不包括选择所有文本行part2=002.

到目前为止,我有:

var res = (from line in File.ReadAllLines(sExecPath + @"\" + sFileName)
           where line == "part1=001"
           select line).ToList();
Run Code Online (Sandbox Code Playgroud)

我试图在linq中使用选项之间,它似乎没有返回任何结果.

var part1= (from prt in File.ReadAllLines(sExecPath + @"\" + sFileName)
            where prt.CompareTo("part1=001") >=0  
            && prt.CompareTo("part=002") >= 0
            select prt);
Run Code Online (Sandbox Code Playgroud)

Chr*_*ain 8

我想你正在寻找TakeWhile:

var linesInPartOne = File
       .ReadAllLines(sExecPath + @"\" + sFileName)
       .SkipWhile(line => !line.StartsWith("**part1="))
       // To skip to part 1 header line, uncomment the line below:
       // Skip(1)
       .TakeWhile(line => !line.StartsWith("**part2="));
Run Code Online (Sandbox Code Playgroud)

为了概括这个以检索任何给定的编号部分,这样的事情会做:

public static IEnumerable<String> ReadHeaderPart(String filePath, int part) {
    return File
        .ReadAllLines(filePath)
        .SkipWhile(line => !line.StartsWith("**part" + part + "="))
        // To skip to part 1 header line, uncomment the line below:
        // Skip(1)
       .TakeWhile(line => 
            !line.StartsWith("**part" + (part + 1) + "=" 
            && 
            !line.StartsWith("end_header")))
       .ToList();
 }
Run Code Online (Sandbox Code Playgroud)

编辑:我有跳过(1)跳过第1部分标题.删除它,因为你似乎想保留该行.


Jef*_*ado 6

public static IEnumerable<string> GetLinesBetween(
    string path,
    string fromInclusive,
    string toExclusive)
{
    return File.ReadLines(path)
        .SkipWhile(line => line != fromInclusive)
        .TakeWhile(line => line != toExclusive);
}

var path = Path.Combine(sExecPath, sFileName); // don't combine paths like that
var result = GetLinesBetween(path, "part1=001", "part2=002").ToList();
Run Code Online (Sandbox Code Playgroud)