44

Possible Duplicate:
How to do SQL Like % in Linq?
Like Operator in Entity Framework?

I'm doing a query like this:

    var matches = from m in db.Customers
        where m.Name == key
        select m;

But I don't need m.Name to be exactly equal to key. I need m.Name to be like key.

I can't find how to recreate the SQL query:

    WHERE m.Name LIKE key

I'm using SQL Server 2008 R2.

How to do it?

Thanks.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • possible duplicates: [Like Operator in Entity Framework?](http://stackoverflow.com/questions/1033007), [How to write like statements...](http://stackoverflow.com/questions/7202217), [Entity Framework v4.1 LIKE](http://stackoverflow.com/questions/6202036), [How to do a SQL LIKE...?](http://stackoverflow.com/questions/7689284),[entity framework and where with like](http://stackoverflow.com/questions/4958082),[How do I do a “like” wildcard comparison in Entity Framework](http://stackoverflow.com/questions/2376191) – mellamokb Aug 02 '12 at 22:20
  • are you familiar with CHARINDEX I will post an example if you would like – MethodMan Aug 02 '12 at 22:22
  • @mellamokb Will see it. Thanks. –  Aug 02 '12 at 22:23
  • @DJKRAZE Post the example please, Thanks. –  Aug 02 '12 at 22:24
  • CHARINDEX is equivalent, with slightly better performance. – MethodMan Aug 02 '12 at 22:25

2 Answers2

72

Would something like this linq query work for you.. ?

var matches = from m in db.Customers
    where m.Name.Contains(key)      
    select m;

this should also work I edited my answer.

Contains is mapped to LIKE '%@p0%' which is case insensitive

Luca Ziegler
  • 3,236
  • 1
  • 22
  • 39
MethodMan
  • 18,625
  • 6
  • 34
  • 52
25
var matches = from m in db.Customers     
    where m.Name.StartsWith(key)
    select m;

Make the search and compare whether the string is either lowercase or uppercase to get the best result since C# is case-sensitive.

var matches = from m in db.Customers     
    where m.Name.ToLower().StartsWith(key.ToLower())
    select m;
Matze
  • 5,100
  • 6
  • 46
  • 69
Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
  • It only covers one case but I can use EndsWith, Contains, etc. Thanks for the idea. –  Aug 02 '12 at 22:30
  • Andrew, Contains works better for my needs but your answer was very useful. Thanks. –  Aug 02 '12 at 23:30