Justin
Justin

Reputation: 6559

Best way to append newline to string except for last

I was looking for the best/cleanest way to iterate over a list of strings and then create a single string of those separated by newlines (except for the last). Like so:

String 1
String 2
String 3

I have written two loops here which has a newline at the end of the string (which I want to avoid) and another that does not. The one does not just doesn't seem "clean" to me. I would think there would be a simpler way to do it so that the logic is nearly as simple as in the example that has a new line to the end of the string.

List<string> errorMessages = new List<string>();
string messages = "";

//Adds newline to last string. Unwanted.
foreach(string msg in errorMessages)
{
    messages += msg + "\n";
}

messages = "";
bool first = true;

//Avoids newline on last string
foreach (string msg in errorMessages)
{
    if(first)
    {
        first = false;
        messages = msg;
    }
    else
    {
        messages += "\n" + msg;
    }
}

Maybe it is wishful thinking, but I would have thought this was a common enough occurrence to warrant a better way to accomplish my goal.

Upvotes: 45

Views: 89467

Answers (5)

jcs
jcs

Reputation: 639

I was having problems using

string.Join(System.Environment.NewLine, errorMessages);

In the page, instead of the new line I was getting \r\n instead. I solved it by using

string.Join("<br>", errorMessages);

Upvotes: 4

Vishal Suthar
Vishal Suthar

Reputation: 17194

using System;

string.Join(Environment.NewLine, errorMessages);

Upvotes: 19

MrFox
MrFox

Reputation: 5126

Use join

string.Join(System.Environment.NewLine, errorMessages);

Upvotes: 100

Ioannis Karadimas
Ioannis Karadimas

Reputation: 7906

The shortest way is to use either .Aggregate(...) or String.Join(...).

var messages = errorMessages.Aggregate((x, y) => x + Environment.NewLine + y);

Or

var messages = String.Join(Environment.NewLine, errorMessages);

Upvotes: 8

Paul Fleming
Paul Fleming

Reputation: 24526

You can use String.Join.

string.Join("\n", errorMessages);

Upvotes: 73

Related Questions