I am reading in lines from a file. I would like to put the lines into a list of strings and then process them. I need some kind of list where I can use .add(line) to add to the list.
What's the best way to define the list?
Once the data is in the list, what's the best way to iterate through it line by line?
Thanks
Use the generic List<T>, comes with .Add:
List<string> lines = new List<string>(File.ReadAllLines("your file"));
lines.Add("My new line!");
Note the static helper method on the System.IO.File static class. I can't remember off-hand, but I think it returns a string array, which you can feed into the constructor of the list.
To iterate, use the foreach construct:
foreach (string line in lines)
{
Console.WriteLine(line);
}
Note that when you have an open iterator on a list (from using foreach, for example) you cannot modify that list:
foreach (string line in lines)
{
Console.WriteLine(line);
lines.Add("Attempting a new line"); // throws an exception.
lines.Remove("Attempting a new line"); // throws an exception.
}
If you wish to be able to modify and iterate at the same time, use a for loop, but be careful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With