开发者

How to write LINQ which function same as SQL like?

开发者 https://www.devze.com 2022-12-10 03:44 出处:网络
How to write linq with same function of following sql Like: select * from table where col li开发者_如何学Goke param?

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

select * from table where col li开发者_如何学Goke param?


Table.Where(t => t.col.Contains(param));

...should do the trick.


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%]


var selection = records.Where (r => r.Col.Contains (param));


var item = from SomeCollection where someCondition select I;


You can use contains clause in Linq which is same as Sql Like. You can find code as following.

var query = from e in emp where e.name.Contains("Mark") select e;

0

精彩评论

暂无评论...
验证码 换一张
取 消