使用LINQ读取文本文件 [英] Reading Text Files with LINQ

查看:68
本文介绍了使用LINQ读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要读取到数组中的文件.

I have a file that I want to read into an array.

string[] allLines = File.ReadAllLines(@"path to file");

我知道我可以遍历数组,找到包含模式的每一行,并显示行号和行本身.

I know that I can iterate through the array and find each line that contains a pattern and display the line number and the line itself.

我的问题是:

是否可以用LINQ做同样的事情?

Is it possible to do the same thing with LINQ?

推荐答案

是的-使用Select()重载并获取索引,我们可以通过将其投影到包含该行本身及其行的匿名类型来实现此目的号码:

Well yes - using the Select() overload that takes an index we can do this by projecting to an anonymous type that contains the line itself as well as its line number:

var targetLines = File.ReadAllLines(@"foo.txt")
                      .Select((x, i) => new { Line = x, LineNumber = i })
                      .Where( x => x.Line.Contains("pattern"))
                      .ToList();

foreach (var line in targetLines)
{
    Console.WriteLine("{0} : {1}", line.LineNumber, line.Line);
}

由于控制台输出是一个副作用,因此应与LINQ查询本身分开.

Since the console output is a side effect it should be separate from the LINQ query itself.

这篇关于使用LINQ读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆