Click here to Skip to main content
15,891,184 members
Articles / Programming Languages / C#

Modifying LINQ Expressions with Rewrite Rules

Rate me:
Please Sign up or sign in to vote.
4.98/5 (29 votes)
18 Mar 2008CPOL24 min read 76K   825   64  
Rewriting query expressions is a simple and yet safe and powerful technique to modify queries dynamically at runtime.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

using Rewrite;
using RewriteSql;

namespace RewriteDemo {
    public partial class Form1: Form {
        public Form1() {
            InitializeComponent();
            this.FillCompareOpCombos();
            this.FillOrderByCombos();
        }

        private void FillOrderByCombos() {
            this.FillOrderByCombo( this.cboSort1 );
            this.FillOrderByCombo( this.cboSort2 );
        }

        private void FillOrderByCombo( ComboBox comboBox ) {
            comboBox.Items.Clear();
            comboBox.Items.AddRange( UserInput.CustomerExtProps );
        }

        private void FillCompareOpCombos() {
            this.FillYearCombo();
            this.FillPropCombo( this.cboWhereProp1 );
            this.FillPropCombo( this.cboWhereProp2 );
        }

        private void FillPropCombo( ComboBox comboBox ) {
            comboBox.Items.Clear();
            comboBox.Items.AddRange( UserInput.CustomerProps );
        }

        private void FillYearCombo() {
            this.cboYears.Items.Clear();
            this.cboYears.Items.Add( "" );
            this.cboYears.Items.AddRange( new object[] { 1996, 1997, 1998 } );
        }

        private void ShowWhereCond( string txt ) {
            StringBuilder sb = new StringBuilder( txt );
            sb.Replace( ".Where(", "\r\n.Where(" );
            sb.Replace( ".Select(", "\r\n.Select(" );
            sb.Replace( ".OrderBy", "\r\n.OrderBy" );
            
            this.txtWhereQuery.Text = sb.ToString();
        }

        private void btnSortRead_Click( object sender, EventArgs e ) {
            IList<CustomerExt> lst = DataAccess.GetCustomersSorted( 
                this.MakeCustomerFilter(), 
                this.MakeCustomerOrderBy(), 
                this.ShowWhereCond );
            if( lst != null ) {
                BindingList<CustomerExt> blc = new BindingList<CustomerExt>( lst );
                this.customerBindingSource.DataSource = blc;
            }
        }

        private Expression<Func<IQueryable<CustomerExt>, IOrderedQueryable<CustomerExt>>> MakeCustomerOrderBy() {
            IOrderByItem<CustomerExt> skey1 = null;
            if( !string.IsNullOrEmpty( this.cboSort1.Text ))
                skey1 = OrderByBuilder<CustomerExt>.BuildGeneric( this.cboSort1.Text, this.chkSortDir1.Checked);
            IOrderByItem<CustomerExt> skey2 = null;
            if( !string.IsNullOrEmpty( this.cboSort2.Text ))
                skey2 = OrderByBuilder<CustomerExt>.BuildGeneric( this.cboSort2.Text, this.chkSortDir2.Checked);

            OrderByItem<CustomerExt,int> skey3 = null;
            if( !string.IsNullOrEmpty( this.cboSortYear.Text ) ) {
                int year;
                if( int.TryParse( this.cboSortYear.Text, out year ) ) {
                    Expression<Func<CustomerExt, int>> expr3 = 
                        z => z.Orders.Count( o => o.OrderDate.HasValue && o.OrderDate.Value.Year == year );
                    // for better readability:
                    expr3 = SimpleRewriter.ApplyOnce( expr3,
                            Rewrite.Rule.Create( () => year, EvaluateLiteral.CreateRhs( year ) ) );
                    skey3 = new OrderByItem<CustomerExt, int>(
                        expr3,
                        true );
                }
            }

            return OrderByBuilder<CustomerExt>.MakeOrderByClause( skey1, skey2, skey3 );
        }

        private Expression<Func<Customer, bool>> MakeCustomerFilter() {
            Expression<Func<Customer, bool>> cityFilter = UserInput.MakeCityFilter( this.txtWhereCity.Text );
            Expression<Func<Customer, bool>> ordersInYearFilter
                = UserInput.MakeOrdersInYearFilter( this.cboYears.Text, this.txtWhereOrderNo.Text );
            Expression<Func<Customer, bool>> generic1 = UserInput.MakeGerericFilter( this.cboWhereProp1.Text, this.cboWhereCompareOp1.Text, this.txtWhereValue1.Text );
            Expression<Func<Customer, bool>> generic2 = UserInput.MakeGerericFilter( this.cboWhereProp2.Text, this.cboWhereCompareOp2.Text, this.txtWhereValue2.Text );

            Expression<Func<Customer, bool>> ret;
            if( this.rbAnd.Checked )
                ret = FilterBuilder.And( generic1, generic2 );
            else
                ret = FilterBuilder.Or( generic1, generic2 );
            if( this.chkNot.Checked )
                ret = FilterBuilder.Not( ret );
            return FilterBuilder.And( ret, cityFilter, ordersInYearFilter );
        }

        private void cboWhereProp2_SelectedIndexChanged( object sender, EventArgs e ) {
            PropertyInfo pi = this.cboWhereProp2.SelectedItem as PropertyInfo;
            if( pi == null)
                return; // -------------->>>>>>>>>>>>>>>>>>>>>
            this.RefreshCompareOpCbo( pi, this.cboWhereCompareOp2 );
        }

        private void RefreshCompareOpCbo( PropertyInfo pi, ComboBox opCbo ) {
            string txt = (string)opCbo.SelectedItem;
            opCbo.Items.Clear();
            opCbo.Text = null;
            var items = UserInput.CompareOps( pi.PropertyType );
            if( items != null )
                opCbo.Items.AddRange( items);
            opCbo.SelectedItem = txt;
        }

        private void cboWhereProp1_SelectedIndexChanged( object sender, EventArgs e ) {
            PropertyInfo pi = this.cboWhereProp1.SelectedItem as PropertyInfo;
            if( pi == null )
                return; // -------------->>>>>>>>>>>>>>>>>>>>>
            this.RefreshCompareOpCbo( pi, this.cboWhereCompareOp1 );
        }
    }
}

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
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions