2017-07-24 52 views
1

這是示例代碼。字符串加入如何忽略空行和LineBreaks

我可以加入所有的字符串,並用空格分隔它們。

如果字符串爲Empty,則加入將忽略,從而阻止雙倍空間。

如何在同一個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))); 

回答

2

只需添加.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"))); 
+1

我會更改'string green = string.Empty;'爲'string green = null;' –

+1

然後添加其他'Where'作爲'.Where(s => s!= null)'來查詢句柄 –

+0

它作品,謝謝。我用'!s.Equals(「\ n \ n」)'。所以如果它是一個獨立的LineBreak而沒有任何其他文本。 –

1

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

指示指定字符串是否爲空,空,或者只包含空格字符。

還修剪其餘的空白空間。

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()) 
); 

這將安全地忽略或爲null,空白或只有空格的項目。它還會移除剩餘物品上的任何空白空間。