使用动态条件读取文本文件

时间:2018-06-06 04:38:50

标签: c# linq

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

可以动态添加搜索条件。

I've tried this SO question

将源修改为动态添加条件:

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吗?

2 个答案:

答案 0 :(得分:4)

你错过了作业:

if(true)
    targetLines = targetLines.Where( x => x.Line.Contains("pattern"));

foreach (var condition in conditions)
{
    targetLines = targetLines.Where(condition....);
}

Where方法不会修改目标变量,而是生成新的可枚举

答案 1 :(得分:3)

您需要执行以下操作

var result = targetLines.Where( x => x.Line.Contains("pattern")).ToList(); 
///var result = targetLines.ToList();

您可以在文档

中查看原因

Enumerable.Where Method (IEnumerable, Func)

  

根据谓词过滤一系列值。

     

返回值

     

IEnumerable ,包含输入序列中的元素   满足条件

相关问题