Linq阅读文本文件

时间:2013-11-21 16:47:36

标签: linq file-io

我有一个内容为:

的文本文件
...
*..
*..
...
The vehicle used are:
*Car(Marathi, Nissan, Toyota)..
*Bikes(Yamaha, Hero Honda)
*...
*...
*...so on..

The items used are...
*..
*..

现在我需要搜索关键词“车辆”并将选项Car(Marathi,Nissan,Toyota)..),Bikes(Yamaha,hero honda)等列入清单。

即。行中“*”之后的所有内容都必须是该列表中的项目。

必须使用Linq或不允许循环的任何其他方式。

1 个答案:

答案 0 :(得分:2)

期望的结果并不是很清楚。

如果您需要List<string>,则包含

"Car(Marathi, Nissan, Toyota).."
"Bikes(Yamaha, Hero Honda)"
"..."
"..."
"...so on..

你可以做到

var result = File.ReadAllLines(@"<pathToYourFile>")
                 //skip lines without "vehicle"
                 .SkipWhile(m => !m.Contains("vehicle"))
                 //skip the line with "vehicle"
                 .Skip(1)
                 //take the following lines starting with an "*"
                 .TakeWhile(m => m.StartsWith("*"))
                 //remove the "*"
                 .Select(m => m.Replace("*", string.Empty))
                 //enumerate to get a List<string>
                 .ToList();
相关问题