Reputation: 2800
What I am trying to achieve:
Want to read text file and store it in a List of Strings. Use second List of string to save if found using regex
I dont know how to tackle this problem but this is what i have done so far.
using (StreamReader content = new StreamReader(@file_To_Read))
{
List <String> newLine = new List <String> ();
string line;
while (line = content.ReadLine()) != null)
//add line to List
newLine.Add(line);
}
Lets say there is text called 'causes' in some of the lines.What I want is now to iterate through the list or lines whatever is easy and store the line in a new list.
Upvotes: 0
Views: 625
Reputation: 152
Following should work
using (StreamReader content = new StreamReader("FileName")) {
List<String> newLine = new List<String>();
while( ! content.EndOfStream)
{
String line = content.ReadLine();
if (line.Contains("causes"))
{
//add line to List
newLine.Add(line);
}
}
}
Upvotes: 0
Reputation: 9394
To read all lines into a List you can write the following:
List<string> lines = File.ReadAllLines(@file_To_Read).ToList();
Now if you want a new list with all lines where the word 'causes' appears you can use the following linq-query:
List<string> causes = lines.Where(line => line.Contains("causes").ToList();
Upvotes: 0
Reputation: 6825
So maybe you want something along these lines?
string[] lines = File.ReadAllLines(filePath); //reads all the lines in the file into the array
string[] causes = lines.Where(line => line.ToLowerInvariant().Contains("causes")).ToArray(); //uses LINQ to filter by predicate
Now you have your lines containing the word "causes" in the array named causes
Hope, that gets you started.
Upvotes: 0
Reputation: 14604
You can filter the list like this
List<string> newlist = newLine.Where(x => x.Contains("your string to match")).ToList();
Upvotes: 2
Reputation: 9713
Have you considered using File.ReadAllLines
?
string[] lines = System.IO.File.ReadAllLines("your_file_path.txt");
Or something more to your requirements.
List<string> lines = System.IO.File.ReadAllLines("your_file_path.txt").ToList();
Upvotes: 1