LINQ2SQL LIKE Command for a phrase

I am trying to get a list of strings where it contains "Britney Spears" and this is what I use

from p in Objects where p.Title.Contains("Britney Spears") select p 

This works well, but if I want to choose a name that is “Britney Jean Spears”, “Britney” Sexy “Spears”, this will not work, so my question is how to insert a “%” wildcard between Britney Spears when holding LINQ2SQL search engine? Thanks.

Regards, Andy.

+6
linq linq-to-sql
source share
3 answers

For this purpose you can use the SqlMethods.Like method.

 from p in Objects where SqlMethods.Like(p.Title, "Britney% Spears") select p 
+13
source share

Just use StartsWith() and EndsWith() to simulate a template. AFAIK, LINQ-to-SQL does not support wildcards.

 from p in Objects where p.Title.StartsWith("Britney") && c.Title.EndsWith("Spears") select p; 

Otherwise, you can run the query directly if you have a more complex template.

 db.ExecuteQuery<MyObject>("SELECT * " + "FROM Objects " + "WHERE Title LIKE 'Britney%Spears'"); 
0
source share

do the same as with direct SQL

you can provide special characters with a like clause such as ".", "%" and "[]"

if this is not good enough, you can use the regular expression, but be careful, as the regular expression will execute as a "client", i.e. it will extract all of this, and then try to limit the results in memory. You can optimize the zerkms method somewhat by doing

 from p in Objects where p.Title.Contains("Britney") && p.Title.Contains("Spears") && regex.Match(p.Title).Success select p 

I have not tested it, but it should run the first two conditions on the SQL server side, and then narrow it down with a regular expression.

-one
source share

All Articles