VB.NET - adding more than 1 line to .contains

I have an HTMLElementCollection that I come across using the For Each Loop option to see if InnerHTML contains specific words. If they contain any of these keywords, it is saved in a file.

Everything works fine, but I was wondering if there is a way to simplify. Here is 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 

Is there anything that will work as follows:

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

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

+2
source share
3 answers

You can write the Extension Method in a line that provides a parameter with several inputs, for example:

  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 

Then you could call it, as in your second example :)

+3
source

1) . One approach was to match the InnerHtml string with a regular expression containing keywords, in the form of 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 in advance.

2) . An alternative approach would be to create a list of your keywords and then compare the InnerHtml string with each of the list items:

 Dim keywords = {"keyword1", "keyword2", "keyword3"} ... For Each keyword As String In keywords If HElement.InnerHtml.Contains(keyword) Then ... Next 

Change The extension method proposed by Rob will result in more elegant code than the # 2 approach described above, IMO.

+2
source

Here is another extension method that makes logic a bit easier with LINQ:

 <Extension()> Public Function MultiContains(str As String, ParamArray values() As String) As Boolean Return values.Any(Function(val) str.Contains(val)) End Function 
0
source

All Articles