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
  • 704,970
  • 168
  • 1,303
  • 1,425
  • 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

70

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
  • 2,727
  • 19
  • 35
MethodMan
  • 18,137
  • 6
  • 33
  • 52
24
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
  • 4,705
  • 6
  • 48
  • 63
Andrew Cooper
  • 31,613
  • 5
  • 76
  • 112