Posterous theme by Cory Watilo

Easy "LIKE" Operations in LINQ to SQL

There are two basic ways to do LIKE operations in LINQ to SQL queries...the easy way and the hard way.  The hard way consists of copious usage of String.StartsWith, String.Contains, and String.EndsWith.  The easy way takes advantage of a handy class called SqlMethods found in the System.Data.Linq.SqlClient namespace.

Using the SqlMethods.Like() method, you can do the following:

var keyword = "Marshmal";
var things = from thing in db.Things
                     where SqlMethods.Like(thing.Name, keyword)
                     select thing;

And if you want to search the start, middle, or end of your string, just tack on the '%' as you would in any normal SQL statement:

var keyword = "mallow";
var things = from thing in db.Things
                     where SqlMethods.Like(thing.Name, "%" + keyword)
                     select thing;

And there you have it...an easy way to find your marshmallows.

| Viewed
times | Favorited 0 times
Filed under:  

0 Comments

Leave a comment...