flamey flamey - 4 years ago 214
C# Question

C#: Looping through lines of multiline string

What is a good way to loop through each line of a multiline string without using much more memory (for example without splitting it into an array)?

Answer Source

I suggest using a combination of StringReader and my LineReader class, which is part of MiscUtil but also available in this StackOverflow answer - you can easily copy just that class into your own utility project. You'd use it like this:

string text = @"First line
second line
third line";

foreach (string line in new LineReader(() => new StringReader(text)))

Looping over all the lines in a body of string data (whether that's a file or whatever) is so common that it shouldn't require the calling code to be testing for null etc :) Having said that, if you do want to do a manual loop, this is the form that I typically prefer over Fredrik's:

using (StringReader reader = new StringReader(input))
    string line;
    while ((line = reader.ReadLine()) != null)
        // Do something with the line

This way you only have to test for nullity once, and you don't have to think about a do/while loop either (which for some reason always takes me more effort to read than a straight while loop).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download