views:

58

answers:

1

I'm building an ASP.NET MVC site that uses LINQ to SQL.

In my search method that has some required and some optional parameters, I want to build a LINQ query while testing for the existence of those optional parameters.


Here's what I'm currently thinking:

using(var db = new DBDataContext())
        {
            IQueryable<Listing> query = null;

            //Handle required parameter
            query = db.Listings.Where(l => l.Lat >= form.bounds.extent1.latitude && l.Lat <= form.bounds.extent2.latitude);

            //Handle optional parameter
            if (numStars != null)
                query = query.Where(l => l.Stars == (int)numStars);

            //Other parameters...

            //Execute query (does this happen here?)
            var result = query.ToList();

            //Process query...

Will this implementation "bundle" the where clauses and then execute the bundled query? If not, how should I implement this feature?

Also, is there anything else that I can improve?

Thanks in advance.

+6  A: 

Yes, the query will only be executed once ToList() is called. If you follow this pattern and are using anonymous types, be aware of OrderBy() returning IOrderedQueryable instead of IQueryable.

Be aware that you are able to just iterate over the IQueryable, you don't have to call ToList to access the data.

Femaref