How to remove blank lines from a C # <string> list?
I am trying to create a subroutine in C # that sorts a list added to a Multi-Line text box. Once this is done, it is possible to delete all empty lines. Can someone tell me how I will do this? here is what i still have, but it doesnβt work at all when i select the field and click the 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); } +7
Jeagr
source share2 answers
If you split the string by '\n' , sortBox1 will not contain the string containing \n . I would just use String.IsNullOrWhiteSpace though:
sortBox1.RemoveAll(string.IsNullOrWhiteSpace); +20
Ryan
source shareYou forgot to sort the lines:
sortBox1.Sort(); The empty line is not "\r\n" , it is a line break. Empty lines are empty lines:
sortBox1.RemoveAll(item => item.Length == 0); You can also remove blank lines when splitting a line:
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); } +7
Guffa
source share