DCSIMG
Linq to SQL Like Operator - Guy Burstein's Blog

Guy Burstein's Blog

Developer Evangelist @ Microsoft

News

Guy Burstein The Bu

Disclaimer
Postings are provided 'As Is' with no warranties and confer no rights.

Guy Burstein LinkedIn Profile

TwitterCounter for @bursteg

Links

Articles

Blogs I Read

Linq to SQL Like Operator

Linq to SQL Like Operator

As a response for customer's question, I decided to write about using Like Operator in Linq to SQL queries.

Linq to SQL Like OperatorStarting from a simple query from Northwind Database;

var query = from c in ctx.Customers

            where c.City == "London"

            select c;

The query that will be sent to the database will be:

SELECT CustomerID, CompanyName, ...
FROM    dbo.Customers
WHERE  City = [London]

There are some ways to write a Linq query that reaults in using Like Operator in the SQL statement:

1. Using String.StartsWith or String.Endswith

Writing the following query:

var query = from c in ctx.Customers

            where c.City.StartsWith("Lo")

            select c;

will generate this SQL statement:

SELECT CustomerID, CompanyName, ...
FROM    dbo.Customers
WHERE  City LIKE [Lo%]

which is exactly what we wanted. Same goes with String.EndsWith.

But, what is we want to query the customer with city name like "L_n%"? (starts with a Capital 'L', than some character, than 'n' and than the rest of the name). Using the query

var query = from c in ctx.Customers

            where c.City.StartsWith("L") && c.City.Contains("n")

            select c;

generates the statement:

SELECT CustomerID, CompanyName, ...
FROM    dbo.Customers
WHERE  City LIKE [L%]
AND      City LIKE [%n%]

which is not exactly what we wanted, and a little more complicated as well.

2. Using SqlMethods.Like method

Digging into System.Data.Linq.SqlClient namespace, I found a little helper class called SqlMethods, which can be very usefull in such scenarios. SqlMethods has a method called Like, that can be used in a Linq to SQL query:

var query = from c in ctx.Customers

            where SqlMethods.Like(c.City, "L_n%")

            select c;

This method gets the string expression to check (the customer's city in this example) and the patterns to test against which is provided in the same way you'd write a LIKE clause in SQL.

Using the above query generated the required SQL statement:

SELECT CustomerID, CompanyName, ...
FROM    dbo.Customers
WHERE  City LIKE [L_n%]

Enjoy!

Comments

Jon Sagara said:

Brilliant!  Thank you.

# February 1, 2008 9:06 AM

Zoli said:

Excellent! That's exactly what I needed.

Thank you.

# February 22, 2008 2:47 PM

WalangAlam said:

thank you. it cured my big headache

# March 29, 2008 9:56 AM

WalangAlam said:

Thank you! it cured my big headache

# March 29, 2008 9:58 AM

Mark Struzinski said:

Perfect! Exactly what I was looking for. Thanks!

# May 5, 2008 3:38 PM

Aqueel Syed said:

Thanks, it was short and sweet.

# May 8, 2008 6:46 AM

Jesse Donat said:

Not exactly what I needed, but lead me on the right path to get what I needed.  Thank you!

# May 29, 2008 3:53 AM

Dazed75 said:

thx, but for equals ignorecase there is a clean solution?

# June 13, 2008 11:48 AM

Jason said:

are you kidding me?  this rocks!  good find!

# June 20, 2008 4:20 AM

Rob said:

now I know, and knowing is half the battle.

# July 1, 2008 11:21 PM

4eburek said:

Thanks a lot!

One question: if I have an int column in sql table and make such LINQ query

Dim res = From r In db.Table _

  Where r.IntColumn.ToString.Contains("25") _

  Select CStr(r.IntColumn) Distinct Take 20

what SQL statement will be generated in this case?

Can I see it somewhere?

# July 2, 2008 7:07 PM

Travis Spencer said:

Here's an example of using the method-oriented (or whatever it's called) syntax:

var searchQuery = someData.Where(s => SqlMethods.Like(s.PhoneNumber, searchString));

# July 14, 2008 7:57 PM

wilsont said:

Thank you very much! your sqlmethod example saved my life...i have been stuck in a statement need field1+'%' like field2 and cannot figure how to do with linq.

# July 31, 2008 6:34 AM

sam said:

Hi, Any idea how to implement a Like for a SQL Text field in LINQ? Basically would like to use a patindex or charindex since its a Text field (not varchar). Thanks

# July 31, 2008 10:26 AM

Jack said:

Wow, it's so easy, thanks a lot, man.

# October 3, 2008 1:32 PM

Neal said:

@Dazed75

Yea, if you use .Contains() then it's case sensative. I prefer to use RegEx to bypass that limitation:

//Searches IList<T> for items matching string

public static IList<Recipe> Search(string searchString)

{

   return (from r in AppCache.Recipes

           where Regex.IsMatch(r.Title, searchString,    

                               RegexOptions.IgnoreCase)

           orderby r.Title

           select r)

       .ToList();

}

# October 23, 2008 10:38 AM

Turgut said:

Thank you...

# December 17, 2008 2:10 AM

Cipper Tech said:

Great, thanks a lot for the sample.

# December 19, 2008 12:25 PM

snich said:

thanks

# December 22, 2008 8:47 AM

Sri said:

Thanks, really i needed it.

# December 24, 2008 1:21 PM

codeburns said:

excellent. thanks a lot

# February 10, 2009 8:04 PM

Chris Charabaruk said:

Wish there was something like this for Entity Framework, too.

# February 19, 2009 11:42 PM

HARTFORMER said:

Thanks!!! Really useful! My Linq pain has been solved! :o)

# March 9, 2009 6:31 PM

Sarvan said:

Thank you very much... it clears my friends headache...

# March 23, 2009 12:54 PM

David said:

It does not work in EDM Query. The sentences are as following:

string likeStr = searchText + "%";

var queryUserID = from c in _commonContext.Accounts

                                 where SqlMethods.Like(c.UserID, likeStr)

                                 select c;

int n = queryUserID.Count();

The exception says: "LINQ to Entities does not recognize the method 'Boolean Like(System.String, System.String)' method "

# April 9, 2009 9:00 PM

Ruud said:

Thanks!

# April 10, 2009 12:44 PM

Rakesh said:

I am using LINQ to extract data from XML.But SqlMethods is not supported over client side.Can u suggest me something?

I have to use wild card chars in LINQ on client side.

# April 14, 2009 7:36 AM

mary said:

 from b in obj.user_DoctorSign

                           from c in obj.sys_HospInfo

                           from d in obj.sys_HospSection

                           join a in obj.user_Doctor

                           on new

                           {

                               b.UserName,

                               c.HospNumber,

                               d.SectionNumber

                           } equals new

                           {

                               a.UserName,

                               a.HospNumber,

                               a.SectionNumber

                           }                    

                           where c.HospName.Contains(HospName) && d.SectionName.Contains(SectionName) && b.ReallyName.Contains(DoctorName)

                           select new

                           {

                               a.UserName,

                               b.ReallyName,

                               a.HospNumber,

                               a.SectionNumber,

                               c.HospName,

                               d.SectionName

                           };

when HosName and SectionName are null, DoctorName is null ,why query.Count()equals 0?

# April 17, 2009 5:17 AM

Joe said:

In this case do you need to sanitize your search string, or will it get treated as a literal?

# May 8, 2009 9:15 PM

Tony said:

Hello, I tryed to use this on Linq to Entities but it failed.

LINQ to Entities does not recognize the method 'Boolean Like(System.String, System.String)

Could you try to help us with this?

# May 24, 2009 5:04 AM

Daniel said:

To see your queries use AnjLab Sql Profiler, it will help you optimize your queries.

# June 13, 2009 4:35 PM

Pham said:

Thanks. That's what i need.

# June 16, 2009 4:24 AM

nick_trcari said:

lisitlidomt.com/riccnavarr.html roracgetri

<a href="trocalz.com/.../a>

[link=ornositlaer.com/lidronalal.html]roracgetri[/link]

[url=rocarodron.com/pasdommo.html]roracgetri[/url]

elteltlidronroc.com/libastrocl.htm zelbasvartrd acelleto

<a herf=darelzelacelrol.com/.../a>

olocnadomletoro.com/olotrzelri.htm rictrel ouboeltald

<a herf=letolicbocchiel.com/.../a>

clizelallinodro.com/trlidro.htm cacnar trtrtarosi

<a herf=troceldomvidarn.com/.../a>

noacelsitaclibo.com/c4tdom.htm tacnarelbon covartrvi

<a herf=lieltnoc4talacc.com/.../a>

erlilacroldompa.com/chiboctrocr.htm pasvarge troctrocerd

<a herf=darzelliololipa.com/.../a>

alliactrsitracr.com/trocrolsitz.htm booloo vardomt

<a herf=rolaldomgetc4tt.com/.../a>

domvarboalelelt.com/boctadeler.htm daracel elrolre

<a herf=cotrocvarlitroc.com/.../a>

roreltarositdel.com/accdronalze.htm taacrelrac viricv

<a herf=lipasletovisitc.com/.../a>

pasoutrcaletoli.com/ccnaalge.htm sitlacazel drondeldron

<a herf=cvartrsitlabasg.com/.../a>

pasacelacdronc4.com/letoroc.htm liboacelsit rocaros

<a herf=dronlizelracvar.com/.../a>

dronlitrdrondro.com/rolaceltrcl.htm trolomonac erlaelt

<a herf=delsitchiormong.com/.../a>

letoelrorobocob.com/darvize.htm oloolov delorellar

<a herf=norelmonrolouli.com/.../a>

cnaacborovarpas.com/cotatrocnod.htm ouricoup getdarol

<a herf=getchirolladeln.com/.../a>

lisitboctasitre.com/monacdomr.htm rocozelmonli trnoelalgetb

<a herf=cdronacourelrel.com/.../a>

letocoboeltdarl.com/tapastrcolil.htm ricdeldarr eltbas

<a herf=ololirelcnaboca.com/.../a>

roricchirolnoer.com/tadron.htm noacelacelli trocrelboc

<a herf=chitrpaszelmont.com/.../a>

elboctrviacchit.com/pasololirol.htm botalig getacace

<a herf=libasgetlabocde.com/.../a>

acaclapasracoug.com/botrel.htm c4tcta elrozel

<a herf=zelvartrocacdar.com/.../a>

lirelletoalvart.com/moncab.htm eracchiolono cobocbocdarv

<a herf=getracdombasrel.com/.../a>

allisitlivilile.com/elnoletol.htm botrleto ercacel

<a herf=alvieltacbasdel.com/.../a>

varbocsitroltro.com/olocnabonoou.htm cnaliri rollapa

<a herf=borodomdelelcob.com/.../a>

zelzeltroccolat.com/troccnasit.htm boriclib libocpastr

<a herf=eltlic4tvidelel.com/.../a>

racmonvielcalav.com/monchicodo.htm lalitrdrond lichiorra

<a herf=domtroclibaslet.com/.../a>

liacboczeldomre.com/aloralorm.htm trocletoo booloeltal

<a herf=laaldartatrrola.com/.../a>

darerzelmoncoc4.com/aceltro.htm monbasr monzele

<a herf=vizelc4tcocoric.com/.../a>

acerdrondronric.com/noerladronc.htm boaltao varzelpasl

<a herf=linoliricbaslit.com/.../a>

erviracricacchi.com/orletorolc.htm baszele letozella

<a herf=dellachieltlali.com/.../a>

racdelouroltaou.com/rovicnalet.htm reldardeltr zelelnoelb

<a herf=oupaslipasbonor.com/.../a>

acdronacelbocou.com/sitvis.htm acelsitri getget

<a herf=libastrocaldarc.com/.../a>

vioracrovarrell.com/racc4tcre.htm cacotrc codarorcnado

<a herf=darlieltcabocta.com/.../a>

cnaorgetlielace.com/trocrollet.htm domboclaac ladronc4t

<a herf=alchiroctrdarli.com/.../a>

trocolobomonolo.com/acelalacelt.htm alzelb c4tdarric

<a herf=lizelrictavarno.com/.../a>

ernoliletodomno.com/trlibassite.htm letovardarc varpasb

<a herf=erelololaricboc.com/.../a>

acacsitrolbocsi.com/dronroln.htm deldronre caalolo

<a herf=trocrolacocovib.com/.../a>

bocvarbasgetlab.com/delzelc.htm roceltvarc4t riccocada

<a herf=erroloualeltrol.com/.../a>

ouricviracdardo.com/rictamo.htm orpasro varc4tletota

<a herf=orviricchilidel.com/.../a>

liletolimongetd.com/oucagete.htm taelda racrelcvarle

<a herf=liliricrolchize.com/.../a>

sitricdroncnaco.com/zellaboc.htm lic4tca dronc4tli

<a herf=botariccovarbas.com/.../a>

cacnanoliacorre.com/eltzelde.htm latr

troclaalcr

# June 30, 2009 12:04 PM

movelove said:

thank you.

It can help me more.

# July 9, 2009 3:23 PM

movelove said:

It can help me more.

thank you.

# July 9, 2009 3:25 PM

Qasim Ali said:

Thank you very much. I was wondering to know the use of like operator in LINQ. Your article give me insights.

# August 7, 2009 11:22 AM

Twitter Trackbacks for Linq to SQL Like Operator - Guy Burstein's Blog [microsoft.co.il] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 Linq to SQL Like Operator - Guy Burstein's Blog         [microsoft.co.il]        on Topsy.com

# December 13, 2009 10:26 AM

mano said:

Hi ,

I am also getting the following error..!! can any one help me.

LINQ to Entities does not recognize the method 'Boolean Like(System.String, System.String)' method, and this method cannot be translated into a store expression.

Thanks in Advance,

mano

# May 6, 2010 3:49 PM

Eudora Parts Hyundai Azera, Cheap Hyundai Azera Cars said:

Pingback from  Eudora Parts Hyundai Azera, Cheap Hyundai Azera Cars

# May 21, 2010 2:53 AM

Day Trips Versailles Paris, Versailles Dining Room Furniture said:

Pingback from  Day Trips Versailles Paris, Versailles Dining Room Furniture

# May 21, 2010 4:05 AM

Dvd 400se 1992 Mercedes, Lexus Ls400 Spec said:

Pingback from  Dvd 400se 1992 Mercedes, Lexus Ls400 Spec

# May 22, 2010 12:21 AM

Browse Our Chevy Uplander Headlight Turn Signal, Uplander Call Car Parts said:

Pingback from  Browse Our Chevy Uplander Headlight Turn Signal, Uplander Call Car Parts

# May 23, 2010 5:56 AM

Cheap Proliant Ml350, Ml350 Headlight Direct Tail Light Assembly - 317.myipgirl.com said:

Pingback from  Cheap Proliant Ml350, Ml350 Headlight Direct Tail Light Assembly - 317.myipgirl.com

# May 23, 2010 11:41 AM

Review Acclaim Car, Acclaim Pt Live - 140.unlockiphone30.net said:

Pingback from  Review Acclaim Car, Acclaim Pt Live - 140.unlockiphone30.net

# May 24, 2010 3:32 PM

C240 Zone Security, C55 Cheap C32 Amg C230 C240 - 398.zapstreaming.com said:

Pingback from  C240 Zone Security, C55 Cheap C32 Amg C230 C240 - 398.zapstreaming.com

# May 24, 2010 5:13 PM

Hayward Navigator Gear Box Parts, 2001 Navigator Cadillac Escalade - 283.unlockiphone30.net said:

Pingback from  Hayward Navigator Gear Box Parts, 2001 Navigator Cadillac Escalade - 283.unlockiphone30.net

# May 24, 2010 9:34 PM

Shobhit Sheel said:

Thanks Dude ... Solved my problem

Stay blessed

# July 25, 2011 3:28 PM

Jeeva said:

Its super ... Really thanks to you

# January 11, 2012 11:33 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: