tags:

views:

37

answers:

4

How to write linq with same function of following sql Like:

select * from table where col like param?
+2  A: 
var selection = records.Where (r => r.Col.Contains (param));
Developer Art
StartsWith also translates to LIKE in SQL according to http://srtsolutions.com/blogs/billwagner/archive/2007/08/12/linq-2-sql-string-functions.aspx
Yuriy Faktorovich
Interesting, however not obvious. Belongs to tricks you need to know. For better maintainability I would stick with "Contains" or "Like" as Dinah suggested.
Developer Art
+4  A: 
Table.Where(t => t.col.Contains(param));

...should do the trick.

Justin Niessner
+2  A: 

From: http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/10/16/linq-to-sql-like-operator.aspx

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%]
Dinah
Is it just me, or is this overkill when Contains does what he needs?
Justin Niessner
@Justin Niessner: no argument here. I did a Google search before any other answers were listed and this is what I found.
Dinah
@Dinah Fair enough. Contains() will usually work for most cases. SqlMethods.Like() is for the more complex cases where the developer wants more control over the generated SQL.
Justin Niessner
Very interesting! System.Data.Linq.SqlClient is not available for silverlight at client site.
KentZhou
A: 
var item = from SomeCollection where someCondition select I;
Daniel A. White