Home > Software design >  How do I check if the string "Edgar Allan Poe" contains any items of List(Of String)?
How do I check if the string "Edgar Allan Poe" contains any items of List(Of String)?

Time:07-13

I have a list of string:

Dim n As New List(Of String)
n.Add("Poe")
n.Add("Shakespeare")

Dim sAuthor As String = "Edgar Allan Poe"

How could I check if sAuthor contains any item of "n"?

I am missing the second argument:

If sAuthor.Contains(n, ...) Then

Thank you!

CodePudding user response:

You could use the Any method (documentation):

If (n.Any(Function(item) sAuthor.Contains(item))) Then
   ' success!
End If

Fiddle: https://dotnetfiddle.net/r7y5Xw

What this does is return a Boolean value based on if any item in the collection evaluates to true based on the predicate.

In this case we are saying: Is any item in my List contained in the variable?

Update

Since the OP indicated that the above is too difficult for them to read/debug, this is how you would do the same thing without using LINQ:

Dim anyMatch As Boolean = False
For Each item In n
    If (sAuthor.Contains(item)) Then
        anyMatch = True
        Exit For
    End If 
Next
If (anyMatch) Then
    ' success!
End If

Fiddle: https://dotnetfiddle.net/DPWo9m

The only (practical) difference between the two is that the above uses LINQ which provides a more concise mechanism of what is used below.

CodePudding user response:

This

    If (From a In n Where sAuthor.Contains(a) Select True Take 1).FirstOrDefault Then
        Stop
    End If
  • Related