Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove blank lines from a C# List<string>?

Tags:

c#

I am trying to create a routine in C# that sorts a list added to a Multi-Line text box. Once that is done, there is an option to remove all blank lines. Can someone tell me how I would go about doing this? here is what I have so far, but it doesn't work at all when I select the box and click sort:

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);
}
like image 483
Jeagr Avatar asked Dec 16 '12 01:12

Jeagr


2 Answers

If you're splitting the string on '\n', sortBox1 won't contain a string containing \n. I would just use String.IsNullOrWhiteSpace, though:

sortBox1.RemoveAll(string.IsNullOrWhiteSpace);
like image 80
Ry- Avatar answered Oct 30 '22 16:10

Ry-


You forgot to sort the lines:

sortBox1.Sort();

A blank line is not "\r\n", that is a line break. Blank lines are empty strings:

sortBox1.RemoveAll(item => item.Length == 0);

You can also remove the blank lines when splitting the string:

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);
}
like image 44
Guffa Avatar answered Oct 30 '22 14:10

Guffa