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

标签 c# string removing-whitespace

这是示例代码。

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

如果字符串为,连接将被忽略,防止出现双空格。

如何在相同的 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")));

关于c# - 字符串连接如何忽略空值和换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45285925/

相关文章:

html - 网站在 iPhone 的屏幕右侧显示空白

python - 用单个空格替换字符串中的多间距 - Python

c# - 直方图/柱形图不显示一直到底部的条形图

c# - 重写 ComboBox 的 Add 方法

string - 如何在 Groovy 中提取子字符串?

c# - 在PHP中,解压后的gz字符串中每个字符后面都有^@,为什么?

java - Java中如何使用String对象解析输入

C# : How to sort a list of object based on a list of string

c# - MySQL连接字符串中的 "pooling=false"是什么意思?

javascript - 使用 XPath 选择带有文本的节点,而不考虑 CasperJS 中的空格