我正在尝试获取包含特定单词的行之前的行列表。这是我的脚本:
private static void Main(string[] args)
{
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("E:\\overview2.srt");
List<string> lines = new List<string>();
while ((line = file.ReadLine()) != null)
{
if (line.Contains("medication"))
{
int x = counter - 1;
Console.WriteLine(x); // this will write the line number not its contents
}
counter++;
}
file.Close();
}
最佳答案
使用 LINQ 方法语法:
var lines = File.ReadLines("E:\\overview2.srt")
.Where(line => line.Contains("medication"))
.ToList();
和 LINQ 关键字语法:
var lines = (
from line in File.ReadLines("E:\\overview2.srt")
where line.Contains("medication")
select line
).ToList();
如果您需要数组,请使用 .ToArray()
而不是 .ToList()
。
此外,如果您只需要迭代一次各行,请不要使用 ToArray
或 ToList
:
var query =
from line in File.ReadLines("E:\\overview2.srt")
where line.Contains("medication")
select line;
foreach (var line in query) {
Console.WriteLine(line);
}
关于c# - 从文件中读取特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14088894/