搜索在文本文件中,直到特定字符串 [英] Searching in text files until specific string
问题描述
我正在写一个程序来搜索文本文件,其中有一个在每一个特定的字符串。我们的目标是忽略该字符串后的一切。我当前的代码读取整个文本文件,并返回一个可枚举,其中的一个术语,发现生成的文件名。
I'm writing a program to search text files, where there's a specific string in each one. The Goal is to ignore everything after that string. My current code reads the whole text file and returns an Enumerable of the resulting file names where a term was found.
var searchResults = files.Where(file => File.ReadAllText(file.FullName).Contains(searchTerm)).Select(file => file.FullName);
这将有可能纳入忽略特定字符串毕竟行? 。因为有成千上万的文件的性能将是重要的。
Would it be possible to incorporate ignoring all lines after that specific string? The Performance would be important as there are thousands of files.
推荐答案
您可以将您的查询更改为:
You can change your query to:
var searchResults = files.Where(file => File.ReadLines(file.FullName).Any(line => line.Contains(searchTerm))
.Select(file => file.FullName));
而不是使用 File.ReadAllText
即可使用 File.ReadLines
这是懒洋洋地评估并停止阅读,当条件满足。
Instead of using File.ReadAllText
you can use File.ReadLines
which is lazily-evaluated and should stop reading when the condition is met.
的 https://msdn.microsoft.com/en-us /library/vstudio/dd383503(v=vs.100).aspx
要使其更快你也可以使用并行LINQ:
To make it faster you can also use Parallel LINQ:
var searchResults = files.AsParallel()
.Where(file => File.ReadLines(file.FullName).Any(line => line.Contains(searchTerm))
.Select(file => file.FullName));
这篇关于搜索在文本文件中,直到特定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!