Reputation: 793
I have a TextBox and want to delete lines if line before = line after.
I have Text like that:
Ab cd ...
Ef Gss ...
EE oo ...
EE oo ... // delete this line
qq ss ff
ok ee ..
I tried with many codes but it removed me all same lines. I just want to remove next same line. Empty lines should be always there.
Code I used:
richTextBox1.Text = string.Join( Environment.NewLine, richTextBox1.Lines.Distinct());
Or:
for (int tx = 0; tx < richTextBox1.Text.Length; tx++)
{
for (int tx1 = tx + 1; tx1 < richTextBox1.Text.Length; tx1++)
{
if (richTextBox1.Lines[tx] == richTextBox1.Lines[tx1])
// something like richTextBox1.Lines[tx1].RemoveAt(tx1);
}
}
Upvotes: 0
Views: 1285
Reputation: 15413
I think the yield operator addresses this problem :
public static IEnumerable<String> GetDistinctLines(IEnumerable<String> lines)
{
string currentLine = null;
foreach (var line in lines)
{
if (line != currentLine)
{
currentLine = line;
yield return currentLine;
}
}
}
then
richTextBox1.Lines = GetDistinctLines(richTextBox1.Lines).ToArray();
Upvotes: 0
Reputation: 945
Code you've posted looks fine for deleting next lines but you are deleting all lines in the rest of text that equals to line in first loop. So in your code
xyz//line0
abc//line1
abc//line2
//line3
hjk//line4
abc//line5
Lines: 2,5 will be removed and if i understand correctly you want to remove only line 2.
my example
line1 text //line index 0
abc //line index 1
abc//delete this line, index 2
abc//delete this line, index 3
step1. line index 2 was deleted
line1 text //line index 0
abc //line index 1
//deleted abc line, previous index 2,
abc//delete this line, index 2, previous index 3
but tx after removing line index 2 will be incremented so you will be at base text line 3 so we need to add tx--
for (int tx = 0; tx < richTextBox1.Text.Length - 1; tx++)
{
if (richTextBox1.Lines[tx] == richTextBox1.Lines[tx+1])
{
// something like richTextBox1.Lines[tx+1].RemoveAt(tx);
tx--;
}
}
}
and if you don't want to remove empty lines you should modify above if statment
if(!String.IsNullOrEmpty(richTextBox1.Lines[tx]) &&richTextBox1.Lines[tx] == richTextBox1.Lines[tx+1])
Upvotes: 0
Reputation: 81253
Try this -
string[] temp = richTextBox1.Lines;
for (int i= 0; i< richTextBox1.Lines.Length - 1; i++)
{
if (richTextBox1.Lines[i] == richTextBox1.Lines[i+ 1]
&& rt.Lines[i] != String.Empty)
{
temp[i] = null;
}
}
richTextBox1.Lines = temp.Where(a => a != null).ToArray();
Upvotes: 2
Reputation: 11063
Try this:
textBox1.Text = string.Join(Environment.NewLine, textBox1.Lines.Distinct());
Upvotes: 0