简体   繁体   English

如何从C#列表中删除空行 <string> ?

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

I am trying to create a routine in C# that sorts a list added to a Multi-Line text box. 我正在尝试在C#中创建一个例程,用于对添加到多行文本框的列表进行排序。 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);
}

If you're splitting the string on '\\n' , sortBox1 won't contain a string containing \\n . 如果要在'\\n'上拆分字符串, sortBox1将不包含包含\\n的字符串。 I would just use String.IsNullOrWhiteSpace , though: 我只想使用String.IsNullOrWhiteSpace

sortBox1.RemoveAll(string.IsNullOrWhiteSpace);

You forgot to sort the lines: 你忘了排序:

sortBox1.Sort();

A blank line is not "\\r\\n" , that is a line break. 空行不是"\\r\\n" ,即换行符。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM