C# 除最后一个外,将换行符附加到字符串的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14140084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:49:11  来源:igfitidea点击:

Best way to append newline to string except for last

c#.netstringrefactoring

提问by Justin

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.

也许这是一厢情愿的想法,但我会认为这是一个足够常见的事件,以保证有更好的方法来实现我的目标。

采纳答案by Paul Fleming

You can use String.Join.

您可以使用String.Join

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

回答by MrFox

Use join

使用连接

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

回答by Ioannis Karadimas

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

最短的方法是使用.Aggregate(...)String.Join(...)

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

Or

或者

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

回答by Vishal Suthar

using System;

string.Join(Environment.NewLine, errorMessages);