从列表中删除所有出现的单词

Remove All Occurrences of Word from a List

给定单词列表...

Word Word Base Ball Ball Apple Cardinal

我将如何删除所有出现的 "Word" 和 "Ball"?我做了一些研究并找到了 list.RemoveAll 函数。我对如何在字符串列表上实现它有点困惑。对于这样的东西,将列表转换为数组会更好吗?

Public Function getListOfWords() As String()
    listOfWords.RemoveAll("the")
    Dim arrayA() As String = listOfWords.ToArray
    Return arrayA
End Function

这是对(字符串的)列表使用 RemoveAll 的方法

Dim words = New List(Of String) From { "Word","Word","Base","Ball","Ball","Apple","Cardinal"}
Dim wordsRemoved = words.RemoveAll(Function(s) s = "Word" OrElse s = "Ball")
Console.WriteLine(wordsRemoved)
For Each s in words
   Console.WriteLine(s)
Next

在此上下文中 RemoveAll requires a function that receives a string and returns a boolean (A Predicate(Of T))。该函数通过重复调用,一个一个地接收序列中包含的元素,应该 return true 删除元素或 false 保留元素

我知道它已得到答复并被接受。但是 bool 谓词似乎有点硬编码,就可扩展性而言,即如果您要删除的单词是 "Word"、"Ball" 和 "Apple" 怎么办?现在必须在代码中更改谓词。我想您可以在谓词中聚合代码,但现在事情变得很愚蠢。

您可能还认为该问题需要 LEFT OUTER JOIN 来解决,这将接受排除列表中的任意数量的元素。这是您可以使用的函数

Public Function getListOfWords(words As IEnumerable(Of String),
                               wordsToRemove As IEnumerable(Of String)) As String()

    Dim wordsRemoved = From word In words
                       Group Join wordToRemove In wordsToRemove
                           On word Equals wordToRemove Into Group
                       From g In Group.DefaultIfEmpty
                       Where g = ""
                       Select word

    Return wordsRemoved.ToArray()
End Function

现在,您可以在任意数量的列表中包含两个集合并调用函数

,而不是双布尔谓词
Dim words = {"Word", "Word", "Base", "Ball", "Ball", "Apple", "Cardinal"}
Dim wordsToRemove = {"Word", "Ball"}
Dim wordsRemoved = getListOfWords(words, wordsToRemove)
For Each s In wordsRemoved
    Console.WriteLine(s)
Next

假设重复项一个接一个地出现:

Dim s = "Word Word Base Ball Ball Apple Cardinal"
Dim pattern = "(?i)(?'word'[a-z]+)(\s+\k'word')"
Dim s2 = Regex.Replace(s, pattern, "${word}")