Adam
Adam

Reputation: 6122

How to check for occurence of string within a list(of String)

I have this code:

Dim listCities As New List(Of String)
listCities.add("this is city London")
listCities.add("this city is called New York")
listCities.add("and another string with a city, this one Berlin")

When I try:

listCities.Contains("London")

It returns false, probably because there is no exact match.

How can I test if listCities contains a string, when that is a substring of a string within the list?

Obviously I prefer not to have to loop through all items in listCities

Upvotes: 0

Views: 77

Answers (4)

With listCities being a List, Contains compares the objects in your list with what you specify (in this case, a string). If you use Contains directly in a String object it will look for that specific string inside the string object.

So, what you need to do is iterate over your list and use Contains, using Any returns a boolean value:

listCities.Any(Function(cet) cet.Contains("London"))

It might be easier to see it like this

For Each city In From city1 In listCities Where city1.Contains("London")
       valueToReturn = True
       Exit For
Next

Upvotes: 0

DarrenMB
DarrenMB

Reputation: 2380

This was what I was thinking, which allows easy reuse as well as understandable long term code format.

    Public Sub Test()
        Dim l As New List(Of String)
                     ' USAGE EXAMPLE
        Dim index As Integer = l.IndexOfContainsText("london")
    End Sub

    <Extension()>
    Public Function IndexOfContainsText(list As List(Of String), ContainsText As String) As Integer
        Dim out As Integer = -1
        For iQ As Integer = 0 To list.Count - 1
            If list(iQ).Contains(ContainsText, StringComparison.InvariantCultureIgnoreCase) Then
                Return iQ
            End If
        Next
        Return out
    End Function

Upvotes: -1

lintmouse
lintmouse

Reputation: 5119

You should be able to achieve it with this:

listCities.Any(Function(x As String) x.Contains("London"));

Upvotes: 0

Steve
Steve

Reputation: 216293

You could use IEnumerable.Any in this way

if listCities.Any(Function(x) x.IndexOf("London") > -1)) Then
   .. true ...

and if you have London spelled in different cases you could use the version of IndexOf that takes a StringComparison.CurrentCultureIgnoreCase parameter

Upvotes: 3

Related Questions