Search code examples
stringvb.netlistremoveall

Remove All Occurrences of Word from a List


Given the list of words...

Word Word Base Ball Ball Apple Cardinal

How would I go about removing all occurrences of "Word" and "Ball"? I've done some research and have found the list.RemoveAll function. I'm just a little confused on how to implement that on a list of strings. Would it be better to convert the list to an array for something such as this?

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

Solution

  • This is how you can use RemoveAll on a List(Of String)

    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
    

    In this context RemoveAll requires a function that receives a string and returns a boolean (A Predicate(Of T)). The function receives, one by one, through repeated calls, the elements contained in the sequence and should return true to remove the element or false to keep the element