2009-04-24

Searching inside strings with LINQ2Objects

I made a search form containing a button and a text box for entering multiple search words, and for excluding words by putting a dash in front of them. So at first I mixed LINQ2Entities with LINQ2Objects, and it didn’t work at all, but after converting from entities to objects (using the .ToList() method), things are working.

Here’s my sample code, as always using Northwind as the database:

protected void SearchButton_Click(object sender, EventArgs e)
{
    using (NORTHWNDEntities context = new NORTHWNDEntities())
    {
        string[] crit = SearchBox.Text.Split(' ');
        List<string> included = new List<string>();
        List<string> excluded = new List<string>();

        for (int i = 0; i < crit.Length; i++)
        {
            if (crit[i].StartsWith("-"))
            {
                //adds the string without the dash to the excluded collection
                excluded.Add(crit[i].Substring(1));
            }
            else
            {
                //adds the string to the included collection
                included.Add(crit[i]);
            }
        }

        List<Products> products = context.Products.ToList(); //converting to objects

        var searchResult =
            from p in products
            where included.Any(i => p.ProductName.Contains(i))
                && !excluded.Any(x => p.ProductName.Contains(x))
            select p;

        ProductsDataList.DataSource = searchResult;
        ProductsDataList.DataBind();
    }
}

No comments:

Post a Comment