For Each removeword In RichTextBox1.Lines
If Not removeword = "" Then
For Each line In LoadedLines.Lines
If line.Contains(removeword) Then
RichTextBox2.Visible = True
LoadedLines.Visible = False
RichTextBox2.Text = RichTextBox2.Text + vbNewLine + line
End If
Next
End If
Next
这是我的代码。
我有一个LoadedLines
RichTextBox
(它包含要编辑的字符串(。
RichTextBox1
包含字符串,它会检查行是否包含其中一个字符串。
问题:
如果我这样运行它,我会得到包含RichTextBox2
中其中一个删除词的所有行。
但是,如果我运行它:
If Not line.Contains(removeword)
它不会将其他行添加到RichTextBox2
,它只是删除了一些removeword
行(非常混乱(。
已经尝试了许多其他方法,例如将其存储在数组中然后写入RichTextBox2
但没有奏效。
覆盖LoadedLines
RichTextBox
不起作用;例如,当我这样做时:
If line.Contains(removeword) Then
line = ""
'(...)
所以你有一个单词列表(假设它们是:Able,Baker,Charlie & Dog(包含在richTextBox1中
。所以我们知道我们在初始运行中总是循环 4 次
然后我们将遍历所有加载的行:
当我们找到其中一个包含 删除词 我们将其添加到另一个富文本框中。
现在让我们用不包含
Loop1 (Able(我们添加所有不包含 able
的行 Loop2 (Baker(我们添加所有不包含 baker 的行(包括包含 Able 的行,因为此迭代正在寻找 Baker(Loop3 (Charlie(
继续此过程。
因此,通过使用 Not,并且由于您没有从 LoadedLine 中删除任何行,因此您将多次添加每一行。唯一不是的情况是当前迭代包含删除词。
您可以使用临时List(Of String)
来存储比较结果,然后验证某个行是否已插入到临时列表中,并且仅在以前未选择该行时才添加新行。
像这样:
Dim LinesList As List(Of String) = New List(Of String)
For Each line As String In LoadedLines.Lines
If line.Length > 0 Then
For Each removeword As String In RichTextBox1.Lines
If (removeword.Length > 0) AndAlso Not (LinesList.Contains(line)) Then
If line.Contains(removeword) Then
LinesList.Add(line)
End If
End If
Next
End If
Next
如果它是中间的,这里有一个可能的LINQ
替代品:
Dim LinesList As List(Of String) =
RichTextBox1.Lines.Where(Function(RemovedWord) RemovedWord.Length > 0).
SelectMany(Function(RemovedWord)
Return LoadedLines.Lines.
Where(Function(ln) ln.Length > 0 AndAlso
ln.Contains(RemovedWord))
End Function).ToList()
使用布尔选择器返回包含要删除的单词的行列表或不包含任何单词的行的列表,使用LINQ
Except()
方法:
Dim ContainsRemovedWords As Boolean = True
If LinesList.Count > 0 Then
RichTextBox2.Visible = True
LoadedLines.Visible = False
If ContainsRemovedWords Then
RichTextBox2.AppendText(String.Join(Environment.NewLine,
LinesList.Select(Function(ln) ln)))
Else
RichTextBox2.AppendText(String.Join(Environment.NewLine,
LoadedLines.Lines.Except(LinesList)))
End If
End If
如果您需要从Except()
列表中删除空行,您可以添加Where()
过滤器:
RichTextBox2.AppendText(String.Join(Environment.NewLine,
LoadedLines.Lines.Except(LinesList2).
Where(Function(ln) ln.Length > 0)))