Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

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();
    }
}

2009-03-21

Linq Flavors

 

I am reading up on Linq, and see that there are a few types of Linq implementations. like for instance LinqToSharePoint or Linq ToFlickr. Reading this makes me think of a few other that could be useful:

  • LinqToWikipedia - for querying for information in an application
  • LinqToLiveSearch (…or Google?)
  • LinqToFacebook
  • LinqToLiveEarth (... or Google Maps) - for finding places