c# - 使用动态条件读取文本文件

标签 c# linq

我想使用 LINQ 搜索文本文件的内容。

可以动态添加搜索条件。

I've tried this SO question .

并修改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/

相关文章:

c# - 在 LinQ Lambda 表达式中连接两个列值

c# - 在 VS2005 中调试时,Page.Flush 出现错误代码为 0x80070057 的 System.Web.HttpException 的原因是什么?

c# - ConcurrentQueue.IsEmpty 是否需要内存屏障?

c# - 使用 C# 将格式从一行复制到另一行

c# - 什么是静态索引器?

c# - 使用 Linq 创建对象列表与创建字典的性能比较?

c# - 从对象列表中获取值列表

c# - 部署时 Log4Net 不记录

linq - 我想要来自此查询的不同或分组数据

c# - 加入嵌套类的 Csharp linq 选择