Reputation: 11
I have a populated multi-line textbox that has a few thousand lines and occassionally has lines like this:
"e8eae9e8eae8e8ebe9e8c5c5c5eae9e8eae8e8ebe9e8eae9e8eae9e8eae8e8ebe9e8eae9e8eae9"
The values can be random, but the common denominator is that they always have over 25 characters and no spaces in the line. I would like to remove any line that meets this specification. I've tried writing the code below but it is giving me index errors.Anyone know of a good way to do this?
string[] lines = txtNotes.Lines;
List<string> tmp = new List<string>(lines);
for (int i = 0; i < lines.GetUpperBound(0); i++)
{
if ((lines[i].Length > 25) && (!(lines[i].Contains(" "))))
{
tmp.RemoveAt(i);
}
}
lines = tmp.ToArray();
txtNotes.Lines = lines;
Upvotes: 1
Views: 176
Reputation: 141905
When you call tmp.RemoveAt(i);
the number elements in the tmp
reduces so you can end up trying to remove element with an index that is not present in the list anymore.
You can switch your loop to run from last element to first:
for (int i = lines.Length -1 ; i > 0; i--)
{
if ((lines[i].Length>25) && (!(lines[i].Contains(" "))))
{
tmp.RemoveAt(i);
}
}
Or just use LINQ. Something like this:
txtNotes.Lines = txtNotes.Lines
.Where(l => l.Length <= 25 || l.Contains(" "))
.ToArray();
Upvotes: 1