Click here to Skip to main content
15,886,578 members
Articles / Programming Languages / C#

LINQ and Dynamic Predicate Construction at Runtime

Rate me:
Please Sign up or sign in to vote.
4.88/5 (29 votes)
13 Aug 2008CPOL7 min read 206.5K   2.2K   87  
Illustrating a multi-predicate injection pattern now possible with the new features of C# 3.0.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LINQDynamicSearchDemo {
    public partial class _Default : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {

        }

        void BindTheQuery() {
            
            // I have this separated in case you want to do paging, we still delay the execution of the query. 
            // That way you can tack on some more expressions before executing it. In this example, I don't do that.

            ResultGrid.DataSource = PrepareDataSource();

        }

        void BindTheData() {

            BindTheQuery();

            /* 
             
             last chance to add stuff to the query. If you do it here, you'll have to cast to IQueryable<Employee>,
             so perhaps do it in BindTheQuery() or PrepareDataSource()
             
             */

            // finally execute the query.
            ResultGrid.DataBind();
        }

        public IQueryable<Employee> PrepareDataSource() {
            
            var predicate = PredicateBuilder.True<Employee>();

            // we start with true, as in, no filters, get all of them.


            // just check the 'checks'... throw in some lambdas

            int emplId = -1;

            // use tryparse to make sure we don't run a bogus query.
            if (cbxUseEmployeeID.Checked &&
                int.TryParse(filterEmployeeId.Text, out emplId) &&
                emplId > 0) {

                // here's how simple it is to add a condition to the query. Still not executing yet, just building a tree.
                predicate = predicate.And(e => e.EmployeeID == emplId);
            }

            if (cbxUseLastName.Checked &&
                !string.IsNullOrEmpty(filterLastName.Text)) {

                // this translates into a LIKE query.
                predicate = predicate.And(e => e.LastName.Contains(filterLastName.Text));
            }

            if (cbxUseFirstName.Checked &&
                !string.IsNullOrEmpty(filterFirstName.Text)) {

                // this translates into a LIKE query.
                predicate = predicate.And(e => e.FirstName.Contains(filterFirstName.Text));
            }

            if (cbxUseTitle.Checked &&
                !string.IsNullOrEmpty(filterTitle.Text)) {

                // this translates into a LIKE query.
                predicate = predicate.And(e => e.Title.Contains(filterTitle.Text));
            }

            DateTime startDateRange = new DateTime(); // default value to avoid 'unassigned use' errors. 
            DateTime endDateRange = new DateTime(); 

            if (cbxUseBirthDate.Checked &&
                DateTime.TryParse(filterBirthDateStart.Text, out startDateRange) &&
                DateTime.TryParse(filterBirthDateEnd.Text, out endDateRange)) {

                // tack on some numeric range testing. I'd have liked to do a between query, but I don't know if
                // there is one that translates in such a way, so we'll just do this:

                predicate = predicate.And(e => e.BirthDate.Value >= startDateRange && e.BirthDate.Value <= endDateRange);
            }

            if (cbxUseAddress.Checked &&
                !string.IsNullOrEmpty(filterAddress.Text)) {

                // this translates into a LIKE query.
                predicate = predicate.And(e => e.Address.Contains(filterAddress.Text));
            }

            if (cbxUseCity.Checked &&
                !string.IsNullOrEmpty(filterCity.Text)) {

                // this translates into a LIKE query.
                predicate = predicate.And(e => e.City.Contains(filterCity.Text));
            }

            if (cbxUseState.Checked &&
                !string.IsNullOrEmpty(filterState.Text)) {

                // this translates into a LIKE query.
                predicate = predicate.And(e => e.Region.Contains(filterState.Text));
            }
            

            if (cbxUsePostalCode.Checked &&
                !string.IsNullOrEmpty(filterPostalCode.Text)) {

                // this translates into a LIKE query.
                predicate = predicate.And(e => e.PostalCode.Contains(filterPostalCode.Text));
            }

            if (cbxUseCountry.Checked &&
                !string.IsNullOrEmpty(filterCountry.Text)) {

                // this translates into a LIKE query.
                predicate = predicate.And(e => e.Country.Contains(filterCountry.Text));
            }

            if (cbxUseHomePhone.Checked &&
                !string.IsNullOrEmpty(filterHomePhone.Text)) {

                // this translates into a LIKE query.
                predicate = predicate.And(e => e.HomePhone.Contains(filterHomePhone.Text));
            }

            if (cbxUseNotes.Checked &&
                !string.IsNullOrEmpty(filterNotes.Text)) {

                // this translates into a LIKE query.
                predicate = predicate.And(e => e.Notes.Contains(filterNotes.Text));
            }

            var results = Config.GetCurrentContext().Employees.Where(predicate);

            // If you are debugging, you can put a breakpoint up there and see the Query by hovering over 'results'.

            return results;
        }

        protected void searchButton_Click(object sender, EventArgs e) {
            BindTheData();
        }

        protected void ResultGrid_PageIndexChanging(object sender, GridViewPageEventArgs e) {
            ResultGrid.PageIndex = e.NewPageIndex;
            BindTheData();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Dave works all day, and stays up all night coding and reading, surfing the intertubes.

Comments and Discussions