tags:

views:

158

answers:

6

Simple Question how to have something like this

customers.where(c=>c.Name **like** "john");

i know this isn not possible but i was wondering how can i have something similar.

thanks in advance.

+4  A: 

The first thought that comes to mind is Regex.IsMatch.

This would come closest to providing the kind of functionality you get from LIKE; for instance with it you could do this:

var matches = people.Where(p => Regex.IsMatch(p.Name, "A.*[mn]"));

foreach (Person match in matches)
{
    Console.WriteLine(match.Name);
}

And get output like this:

Adam
Aaron
Aidan

Going with string.Contains as others have suggested is almost certainly preferable if your intention is simply to look for a specific substring within Name.

Dan Tao
and now you have _two_ problems :).
Phil
@Phil: Indeed, I don't know how I feel about even posting this answer. I'm leaving it as an option, anyway. Maybe someone will come along and point out that it is a horrible suggestion; I don't know.
Dan Tao
Just wondering, why is this a horrible suggestion? :/
Michael
@Michael, it's not a horrible suggestion I'm just refering to a famous quote: *Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.*
Phil
Oh, I see. Knowing RegExes I even understand why the quote got famous :-)
Michael
+11  A: 
customers.Where(c => c.Name.Contains("john"));
Tom Vervoort
+1. Perfect. Works with both LINQ over enumerables (LINQ to Object) as LINQ over expression trees (LINQ to SQL, LINQ to Entities, etc).
Steven
+2  A: 

Actually you can generate like statements.

Look here and here for a good examples.

madcapnmckay
+10  A: 

Use SqlMethods.Like:

customers.Where(c => SqlMethods.Like(c.Name, "%john%")); 

Explanation:

The compiler will generate an expression tree from the statement above. Since LIKE is a SQL specific construct and not common to all LINQ Query providers, the SqlMethods class and its members are used as a "hint" for the expression compiler (compiles expression trees to SQL) to emit a LIKE statement.

Johannes Rudolph
This will (of course) only work with LINQ to SQL, not with LINQ to Entities nor with 'LINQ to Enumerable' a.k.a. LINQ to Objects.
Steven
Yes, I'm assuming that he's using LinqToSql. I felt using string.contains is just too obvious?!
Johannes Rudolph
A: 

Use Regex.IsMatch in your where statement or for a more simpler version without wildcards etc.:

customers.where(c=>c.Name.Contains("john"));
bitbonk
+2  A: 
using System.Data.Linq.SqlClient;
...
customers.where(c=>SqlMethods.Like(c.Name, "john"));
Andrei