2012-12-16 47 views
7

我正在尝试在C#中创建一个例程,它将添加到多行文本框中的列表排序。完成后,可以选择删除所有空白行。有人能告诉我如何去做这件事吗?这里是我到目前为止,但是当我选择框不会在所有的工作,然后点击排序:如何从C#列表中删除空白行<string>?

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

回答

20

如果你对分裂的'\n'字符串,sortBox1将不包含包含字符串\n。我只想用String.IsNullOrWhiteSpace,虽然:

sortBox1.RemoveAll(string.IsNullOrWhiteSpace); 
7

你忘了行排序:

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