I suggest using a combination of StringReader and my LineReader class, which is part of MiscUtil , but is also available in https://stackoverflow.com/a/166269/167/ - you can easily copy only this class into your own utility project. You would use it as follows:
string text = @"First line second line third line"; foreach (string line in new LineReader(() => new StringReader(text))) { Console.WriteLine(line); }
Looping over all the lines in the string data (whether it be a file or something else) is so common that it does not require the calling code to test zero, etc. :) Having said that, if you want to make a manual loop, this is a form, which I usually prefer over Fredrik's:
using (StringReader reader = new StringReader(input)) { string line; while ((line = reader.ReadLine()) != null) {
That way, you only need to check the nullity value once, and you donβt need to think about the do / while loop (which for some reason always takes more effort to read than the direct while loop).
Jon Skeet Sep 30 '09 at 19:41 2009-09-30 19:41
source share