views:

187

answers:

2

I have an HTMLElementCollection that I'm going through using a For Each Loop to see if the InnerHTML contains certain words. If they do contain any of those keywords it gets saved into a file.

Everything works fine but I was wondering if there is a way to simplify. Here's a sample

For Each Helement As HtmlElement In elements

     If Helement.InnerHtml.Contains("keyword1") Or Helement.InnerHtml.Contains("keyword2") Or Helement.InnerHtml.Contains("keyword3") Or Helement.InnerHtml.Contains("keyword4") Or Helement.InnerHtml.Contains("keyword5") = True Then
         ' THE CODE TO COPY TO FILE
     End If

Next Helement

Does anything exist that would work like:

If Helement.InnerHtml.Contains("keyword1", "keyword2", "keyword3", "keyword4", "keyword5")

The way I'm doing it now just seems wasteful, and I'm pretty OCD about it.

+1  A: 

1) One approach would be to match the InnerHtml string against a regular expression containing the keywords as a list of alternatives:

Imports System.Text.RegularExpressions

Dim keywords As New Regex("keyword1|keyword2|keyword3")

...

If keywords.IsMatch(HElement.InnerHtml) Then ...

This should work well if you know all your keywords beforehand.

2) An alternative approach would be to build a list of your keywords and then compare the InnerHtml string against each of the list's elements:

Dim keywords = New String() {"keyword1", "keyword2", "keyword3"}

...

For Each keyword As String In keywords
    If HElement.InnerHtml.Contains(keyword) Then ...
Next

Edit: The extension method suggested by Rob would result in more elegant code than the above approach #2, IMO.

stakx
+2  A: 

You could write an Extension Method to string that provides a multi-input option, such as:

 Public Module StringExtensionMethods
     Private Sub New()
     End Sub
     <System.Runtime.CompilerServices.Extension> _
     Public Function Contains(ByVal str As String, ByVal ParamArray values As String()) As Boolean
         For Each value In values
             If str.Contains(value) Then
                 Return True
             End If
         Next
         Return False
     End Function
 End Module

You could then call that instead, as in your second example :)

Rob
Consider instead: Return values.Any(Function(val) str.Contains(val))
Luhmann