How to implement SQL LIKE keyword in LINQ to SQL

By Mohammad Mahdi Ramezanpour at November 17, 2008 18:27
Filed Under: .NET General, LINQ, SQL Server

It’s about a year that .NET framework 3.5 has been released. Most of companies are still using SqlConnection, SqlCommand, SqlDataAdaptor, etc. in order to manager their data connections. About 5 month ago I started posting articles about LINQ to SQL and ways you can use in order to use LINQ as a very powerful data source.

In this post I’m going to show how you can implement SQL “LIKE” keyword in LINQ to SQL.

As you may know, SQL Server has 3 kind of LIKE keywords (%LIKE, %LIKE% and LIKE%). For each of these types, you have to use of specific LINQ to SQL:

LIKE%:

LIKE% selects all rows that start with an expression, for example:

SELECT Title, LoginID FROM HumanResources.Employee 
WHERE Title LIKE N'Acc%'

Here is the return value:

SQL result after using LIKE keyword

In order to implement such a thing in LINQ to SQL you have to use the StartsWith() method like following:

private void ImplementStartsWith()
        {
            AWDataContext db = new AWDataContext();
            var i = from item in db.Employees
                    where item.Title.StartsWith("Acc")
                    select new {Title = item.Title, UserName = item.LoginID };
            dataGridView1.DataSource = i;
        }

%LIKE:

%LIKE selects all rows that end with an expression. For example, I want to have all managers so I select titles that end with “Manager”. EndsWith() method will help you out for this:

private void ImplementEndsWith()
        {
            AWDataContext db = new AWDataContext();
            var i = from item in db.Employees
                    where item.Title.EndsWith("Manager")
                    select new { Title = item.Title, UserName = item.LoginID };
            dataGridView1.DataSource = i;
        }

%LIKE%:

This like is the most useful like type that is using for searches. If you want to have all rows that contain an expression, you must use Contains() method:

private void ImplementContains()
{
        AWDataContext db = new AWDataContext();
        var i = from item in db.Employees
                where item.Title.EndsWith("Specialist")
                select new { Title = item.Title, UserName = item.LoginID };
        dataGridView1.DataSource = i;
}

Comments

7/23/2009 1:03:24 AM #

Charles Hubert

I think you have to improve a bit the design and usability of your blog.

Charles Hubert United States

Comments are closed

Currently Reading

Quote of the day

Send Persian SMS