How can I create a list of strings in C#
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 l开发者_运维百科ist?
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.
List<string> list = new List<string>(); // list creation
List<string> list2 = new List<string>(File.ReadAllLines("filename")) // instant reading
list.Add("Hello world"); // adding a string
foreach (string item in list) // iterating over a list
Console.WriteLine(item);
Use File.ReadAllLines method and for
or foreach
iterators
Can do something like this
string path = "MyFile.txt";
string[] lines = File.ReadAllLines(path);
List<string> listOfLines = new List<string>();
foreach(string str in lines)
{
listOfLines.Add(str);
}
That example pretty much lifted from http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx#Y1113
If the file is small, you can do the ReadAllLines() approach that others are suggesting. However, for large files this will not behave well.
Alternately, you could do something like this:
class Program
{
static void Main(string[] args)
{
var myList = new List<string>;
using (var sw = new StreamReader(@"c:\foo.txt"))
{
while (true)
{
string line = sw.ReadLine();
if (line == null)
break;
myList.Add(line);
}
}
}
}
You can do it in only one line :
foreach (string line in Files.ReadAllLines("file"))
{
// ...
}
You could use File.ReadAllLines to read an entire file, and then a foreach loop to process them. For example:
string[] lines=File.ReadAllLines("somefile.txt");
foreach(string line in lines)
{
Process(line);
}
精彩评论