我正在开发一个应用程序来执行文件内部的搜索,我编写了以下代码来执行此操作:
foreach (var file in filesInDir)
{
string[] lines = File.ReadAllLines(file.FullName);
for(int i=0;i<lines.Length;i++)
if(lines[i].Contains("123456789"))
Console.Write("File: {0}\nLine: {1}", file.FullName, i + 1);
}
所以,我想知道如何使用Linq完成这项研究,这有可能吗?
答案 0 :(得分:8)
选择该行以及索引(行号),然后查询您的字符串,然后选择LineNo
之类的:
var result = lines.Select((r, i) => new { line = r, index = i })
.Where(r => r.line.Contains("123456789"))
.Select(r => new { LineNo = r.index });
显示:
foreach(var item in result)
Console.Write("File: {0}\nLine: {1}", file.FullName, item.LineNo);
修改强>
您还可以对目录中的所有文件执行以下操作,例如:
var result = filesInDir.Select(t => new { lines = File.ReadAllLines(t.FullName), FileName = t.Name })
.Select((r, i) => new { line = r.lines, index = i, FileName = r.FileName })
.Where(r => r.line.Contains("123456789"))
.Select(r => new { FileName = r.FileName, LineNo = r.index });
然后显示:
foreach (var item in result)
Console.Write("File: {0}\nLine: {1}", item.FileName, item.LineNo);
答案 1 :(得分:2)
var lines = File.ReadAllLines(file.FullName).ToList();
lines.Where(x=>x.Contains("123456790")).ToList().ForEach(x=>Console.Write("File: {0}\nLine: {1}", x.FullName, lines.IndexOf(x)));