字符串连接如何忽略空值和换行符

String Join How to Ignore Both Empty and LineBreaks

这是示例代码。

我能够连接所有字符串并用 spaces 分隔它们。

如果字符串是 Empty,连接将忽略,防止双重 space。

如何同时忽略相同 ColorList.Where() 参数中的换行符 \n

string red = "Red";
string blue = "Blue";
string yellow = "\n\n";
string green = string.Empty;

List<string> ColorList = new List<string>()
{
    red,
    blue,
    yellow,
    green
};

string colors = string.Join(" ", ColorList.Where(s => !string.IsNullOrEmpty(s)));

只需将 .Where(s => !s.Contains("\n")) 添加到您的查询中:

string red = "Red";
string blue = "Blue";
string yellow = "\n\n";
string green = string.Empty;

 List<string> ColorList = new List<string>()
{
    red,
    blue,
    yellow,
    green
};

string colors = string.Join(" ", ColorList.Where(s => !string.IsNullOrEmpty(s)).Where(s => !s.Contains("\n")));

你也可以使用String.IsNullOrWhiteSpace Method (String)

Indicates whether a specified string is null, empty, or consists only of white-space characters.

还有 Trim 任何白色 space 其余的。

string red = "Red";
string blue = "Blue";
string yellow = "\n\n";
string green = string.Empty;
string black = null;

var ColorList = new List<string>()
{
    red,
    blue,
    yellow,
    green,
    black
};

//Red Blue
string colors = string.Join(" ", 
    ColorList.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.Trim())
);

这将安全地忽略或为空、为空或只有白色 space 的项目。它还将删除剩余项目上的任何杂散白色 spaces。