Archive for the ‘linq to SQL’ Tag

wildcard searches using LINQ

recently work on ASP.Net Project.
use LINQ as my Query Language, this is my favorite  feature of .Net 3.5.
original I write my Search Query like this:
var searchQuery=from a in db.customer
where a.ID=param
select a;

this is not a wildcard search query , you only can get the result when parameter(search key word)  exactly same with database record. So far customer no complain the search engine, because they don’t know and my boss also din ask me to do wildcard searches. but as a programmer, you do not want to create a system without standard. My boss always blame me do redundant work,  customer won’t appreciate it. But I not care, just a minor change only.

to do wildcard searches in sql is use LIKE operation and wildcard characters( %), I believe you familiar than me if you still using ADO.NET to query your database. it something like this:

SELECT *
FROM Customers
WHERE Phone LIKE '%param%' 

It's fairly simple, if you using LINQ, you just need to know .StartsWith, .EndsWith, and .Contains this 3 syntaxes. below show comparison of LINQ and SQL:

LINQ

SQL

StartsWith
var query=from a in db.customer

where a.ID.StartsWith(param)

select a;

Select*

from Customer

where id=param%;

EndsWith
var query=from a in db.customer

where a.ID.EndsWith(param)

select a;

Select*

from Customer

where id=%param;

Contains
var query=from a in db.customer

where a.ID.Contains(param)

select a;

Select*

from Customer

where id=%param%;

it look longer than SQL, but you don’t forget when you do binding in .net project you still need write very very long ADO.NET statement. Compare to ADO.NET, LINQ(actually also part of ADO.NET) is simply and easy, just 3 sentence to create bindable query.

So Far, I just know this method to do wildcard search, any better suggestion?

加关注

Get every new post delivered to your Inbox.