[英]How to remove blank lines from a C# List<string>?
我正在嘗試在C#中創建一個例程,用於對添加到多行文本框的列表進行排序。 完成后,可以選擇刪除所有空行。 有人能告訴我怎么做這個嗎? 這是我到目前為止所做的,但是當我選擇框並點擊排序時它根本不起作用:
private void button1_Click(object sender, EventArgs e)
{
char[] delimiterChars = { ',',' ',':','|','\n' };
List<string> sortBox1 = new List<string>(textBox2.Text.Split(delimiterChars));
if (checkBox3.Checked) //REMOVE BLANK LINES FROM LIST
{
sortBox1.RemoveAll(item => item == "\r\n");
}
textBox3.Text = string.Join("\r\n", sortBox1);
}
如果要在'\\n'
上拆分字符串, sortBox1
將不包含包含\\n
的字符串。 我只想使用String.IsNullOrWhiteSpace
:
sortBox1.RemoveAll(string.IsNullOrWhiteSpace);
你忘了排序:
sortBox1.Sort();
空行不是"\\r\\n"
,即換行符。 空行是空字符串:
sortBox1.RemoveAll(item => item.Length == 0);
您還可以在拆分字符串時刪除空行:
private void button1_Click(object sender, EventArgs e) {
char[] delimiterChars = { ',',' ',':','|','\n' };
StringSplitOptions options;
if (checkBox3.Checked) {
options = StringSplitOptions.RemoveEmptyEntries;
} else {
options = StringSplitOptions.None;
}
List<string> sortBox1 = new List<string>(textBox2.Text.Split(delimiterChars, options));
sortBox1.Sort();
textBox3.Text = string.Join("\r\n", sortBox1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.