Bob
Bob

Reputation: 1396

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

Upvotes: 0

Views: 493

Answers (3)

JohnyL
JohnyL

Reputation: 7132

Assuming duplicates go one right after another:

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

Upvotes: 0

djv
djv

Reputation: 15774

I know it's answered and accepted. But the bool predicate seems a little hard-coded, in terms of scaleability i.e. what if the words you wanted to remove were "Word", "Ball", and "Apple"? Now the predicate must be changed in code. I suppose you could aggregate the code in the predicate, but now things are getting silly.

You may also recognize the problem as needing a LEFT OUTER JOIN to solve it, which would accept any number of elements in the exclusion list. Here is a function you could use

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

And now, instead of the two-bool predicate, you can contain both sets in lists of any quantity and call the 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

Upvotes: 1

Steve
Steve

Reputation: 216273

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

Upvotes: 4

Related Questions