我正在尝试删除所有具有相同文本字符串的行。 例如,过滤后的字符串是“MyString”。如果“MyString”在RhichTextBox中出现多次,只需从RichTextBox中删除整个文本行。因此,只有一行“MyString”首次出现。将删除具有相同字符串的所有其他行。
以下是我的尝试:
Dim myfilteredstring As String
myfilteredstring = "MyString"
Dim rtblines As New List(Of String)(RichTextBox1.Lines)
Dim Line1 As String
Dim Line2 As String
Dim j As Integer
For j = 0 To RichTextBox1.Lines.Count - 1
Line1 = RichTextBox1.Lines(j).ToString
Dim k As Integer
For k = 0 To RichTextBox1.Lines.Count - 1
Line2 = RichTextBox1.Lines(k).ToString
If Line1.Contains(myfilteredstring) Then
If Line2.Contains(myfilteredstring) Then
rtblines.Remove(Line2)
End If
End If
Next
Next
答案 0 :(得分:1)
这应该这样做。代码获取第一次出现的索引。然后通过列表向后工作到第一次出现后的行并删除它们。并用更新的行列表替换RTB的内容。
Dim myfilteredstring As String
myfilteredstring = "MyString"
Dim rtblines As New List(Of String)(RichTextBox1.Lines)
Dim firstlineFound As Boolean = False
Dim indexOfFirstLine As Integer = -1
For i As Integer = 0 To rtblines.Count - 1
If rtblines(i).Contains(myfilteredstring) Then
indexOfFirstLine = i
Exit For
End If
Next
For i As Integer = rtblines.Count - 1 To indexOfFirstLine + 1 Step -1
If rtblines(i).Contains(myfilteredstring) Then
rtblines.RemoveAt(i)
End If
Next
RichTextBox1.Lines = rtblines.ToArray
答案 1 :(得分:-1)
我不确定你想做什么。这将删除包含MyString
Dim firstAppearance As String = RichTextBox1.Lines.Where(Function(line As String) line.Contains("MyString")).First()
RichTextBox1.Lines = RichTextBox1.Lines.Where(Function(line As String) (Not line.Contains("MyString")) OrElse (line = firstAppearance)).ToArray()