我想使用 LINQ 搜索文本文件的内容。
可以动态添加搜索条件。
并修改source为动态添加where条件:
var targetLines = File.ReadAllLines(@"foo.txt")
.Select((x, i) => new { Line = x, LineNumber = i });
if(true)
targetLines.Where( x => x.Line.Contains("pattern"));
foreach (int condition in conditions)
targetLines.Where(condition....);
var result = targetLines.ToList();
foreach (var line in result)
Console.WriteLine("{0} : {1}", line.LineNumber, line.Line);
但它不起作用,条件未应用于输出。
我可以使用 LINQ 来完成吗?
最佳答案
你错过了作业:
if(true)
targetLines = targetLines.Where( x => x.Line.Contains("pattern"));
foreach (var condition in conditions)
{
targetLines = targetLines.Where(condition....);
}
Where
方法不会修改您的目标变量,而是生成新的可枚举变量
关于c# - 使用动态条件读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50712346/