C#: Looping through lines of multiline string

Viewed 129012

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)?

7 Answers

Try using String.Split Method:

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

foreach (string line in text.Split('\n'))
{
    // do something
}

Sometimes I think we can overcomplicate the solution just to avoid repeating one line of code. This is the reason I landed on this question in the first place.

After thinking about it for a bit I came to the conclusion that the simplest solution is to repeat the ReadLine before and inside the loop.

using (var stringReader = new StringReader(input))
{
    var line = await stringReader.ReadLineAsync();

    while (line != null)
    {
        // do something
        line = await stringReader.ReadLineAsync();
    }
}

I realize this might be considered to not follow the DRY principle, but I think it's worth considering given the simplicity.

Related