这是示例代码。
我能够连接所有字符串并用空格分隔它们。
如果字符串为空
,连接将被忽略,防止出现双空格。
如何在相同的 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/