代码之家  ›  专栏  ›  技术社区  ›  Bob

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

  •  0
  • Bob  · 技术社区  · 8 年前

    给出单词列表。。。

    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
    
    3 回复  |  直到 8 年前
        1
  •  4
  •   Steve    8 年前

    这是如何在列表(字符串)上使用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 需要接收字符串并返回布尔值的函数( A Predicate(Of T) ). 函数通过重复调用一个接一个地接收序列中包含的元素,并应返回true以删除该元素,或返回false以保留该元素

        2
  •  1
  •   djv    8 年前

    我知道它已经被回答和接受了。但是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
    
        3
  •  0
  •   JohnyL    8 年前

    假设副本一个接一个地出现:

    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}")