文本文件格式
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();
我试图在linq中使用选项之间,它似乎没有返回任何结果。
var part1= (from prt in File.ReadAllLines(sExecPath + @"\" + sFileName)
where prt.CompareTo("part1=001") >=0
&& prt.CompareTo("part=002") >= 0
select prt);
答案 0 :(得分: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="));
要概括这一点以检索任何给定的编号部分,可以这样做:
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();
}
编辑:我在那里跳过了Skip(1)跳过第1部分标题。删除它,因为你似乎想保留该行。
答案 1 :(得分: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();
答案 2 :(得分:1)
最简单,最直接的解决方案就是这样:
var lines = File.ReadAllLines(@"C:\Sample.txt").
SkipWhile(line=>!line.Contains("part1")).
Skip(1).TakeWhile(line=>!line.Contains("part2"));
它会返回您想要的结果。 逻辑很简单:
SkipWhile
行,直到遇到包含“part1”的行Skip(1)
之后(因为它实际上是包含“part1”字符串的那个)Take
那些直到到达包含“part2”的行。答案 3 :(得分:0)
Linq可能不是你最好的选择。试试吧
var lines = File.ReadAllLines(filename);
List<string> linesICareABout = new List<string>();
for(int i = 0; !linesICareAbout[i].Contains("part2=002"); ++i)
{
linesICareABout.Add(lines[i]);
}
然后用你读过的行做你想做的事。
但是,如果您真的致力于使用Linq,请尝试TakeWhile