7.3. Filtering with an Eye on Strings

Visual Basic gives you several ways to filter the results of a query based on what's in a string of text. This section shows the use of operators and methods, including Like, Contains(), EndsWith(), and StartsWith().

7.3.1. Choosing what you Like

The follow code examines the ASP.NET ServerVariables collection in the Request object and uses the Like keyword to look for the text SERVER.

Dim q = From sv As String In Request.ServerVariables _
  Select sv _
  Where sv Like "*SERVER*"

GridView1.DataSource = q
GridView1.DataBind()

The asterisks on both ends of *SERVER* indicate that any number of characters (or none) can exist before the string as well as after the string. The query returns nine members of the collection. The following partial results show that the location of SERVER within the text isn't important. What matters is that the string you're testing matches the pattrn:

CERT_SERVER_ISSUER
...
SERVER_SOFTWARE

In the preceding example, if you drop the first asterisk — as in Where sv Like "SERVER*" — the query returns all items starting with SERVER.

7.3.2. Investigating what the query Contains()

The Contains() function is similar to Like in that it allows you to look inside a string and return the items that match. In the following code, Contains() examines each ProductName value and returns those that have the letters co within them, such as Chocolade and Ipoh Coffee.

Dim dc As New NWDataClassesDataContext Dim q = From p In dc.Products _ ...

Get ASP.NET 3.5 For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.