Finding list item that matches a pattern
This should be easy, but I have been beating my head against this for a while and need help…
In Visual Basic, I have created a list of strings, each string having the same number of characters. For example, my list might contain: AABCF, CFACA, BBEEE, AAAAF. In now need to ‘prune’ the list by removing all strings that have specific letters at two specific places, for example “A??C?”. In this case, the pattern matches the first string in the list and it is to be removed.
Seems simple, but I cannot figure this out. Please help!
Re: Finding list item that matches a pattern
You can use this function to match each item in a collection by a given pattern:
Code:
Private Function MatchPattern(collection As IEnumerable(Of String), pattern As String) As IEnumerable(Of String)
Dim specificMatches = New List(Of Integer)
For index = 0 To pattern.Length - 1
If (pattern(index) <> "?") Then
specificMatches.Add(index)
End If
Next
Return collection.Where(Function(item) specificMatches.All(Function(index) item(index) = pattern(index)))
End Function
To use it in your case, you would get the items that match the pattern and then set your collection to be every item that isn't in the returned result:
Code:
Dim items = { "AABCF", "CFACA", "BBEEE", "AAAAF" }
Dim matchedItems = MatchPattern(items, "A??C?")
items = items.Where(Function(item) Not matchedItems.Contains(item)).ToArray()
Re: Finding list item that matches a pattern
Re: Finding list item that matches a pattern
@paul - Thank, I forget about the RemoveAll method. Do you know if there is a method to get every index of an item in a collection? The reason I use a For/Next loop in my suggestion is because IndexOf is only going to return the first instance.
Re: Finding list item that matches a pattern
Not a one liner, as far as I know... You could use Linq. I’m not at my PC at the moment
Re: Finding list item that matches a pattern
dday9,
Thanks for the pointer. My code - in a subroutine, which works, looks like this:
Code:
strPattern = "A??C?" ' as an example
For i = ListOfSolution.Count - 1 To 0 Step -1
If ListOfSolution(i) Like strPattern Then
ListOfSolution.RemoveAt(i)
End If
Next i
Re: Finding list item that matches a pattern
As a general rule, I would suggest avoiding functions that live in the Microsoft.VisualBasic namespace.
If you wanted a one-liner to replace your method, it could look something like (free-typed):
Code:
ListOfSolution = ListOfSolution.Where(Function(item) Not (item Like strPattern)).ToList()