Converting SQL to LINQ, Part 10: Like (Bill Horst)

This post assumes you’ve read my previous Converting SQL to LINQ posts.

 

I haven’t had much in the way of specific requests for more LINQ posts, so I’d still welcome any suggestions that people want to offer.  I did get one request about how to mimic the LIKE keyword functionality in VB LINQ.

 

In SQL, the LIKE keyword compares a string field against a pattern and returns a Boolean value representing whether the string matches the pattern.  For example, if I wanted to select every customer in the 206 area code, I could use this SQL query:

 

SQL

SELECT *

FROM CustomerTable

WHERE Phone LIKE ‘206*’

 

 

The LIKE expression can include certain wildcard characters, which may differ from system to system.  In the above example, * matches any string, so ‘206*’ represents any string that begins with 206.

 

VB happens to include a Like operator, so this is an easy conversion to make.  The LINQ version of this above SQL expression is specified below:

 

VB

From Contact In CustomerTable _

Where Contact.Phone Like “206*”

 

 

The VB Like keyword has the following wildcards:

          ?                  Matches any single character

          *                  Matches zero or more characters

          #                 Matches any single digit

          [ charlist ]     Matches any single character in the charlist

          [! charlist ]    Matches any single character not in the charlist

 

More extensive documentation of the Like operator can be found here.

 

      Bill Horst, VB IDE Test