23 December 2011

Dynamically add conditions in linq

Written by Amit Panchal, Posted in Blog

Dynamically apply filters on multiple columns in your linq query with the help of PredicateBuilder class

Sometimes you may want to put "where" conditions in your LINQ query based on some criteria. You want to add dynamically filters in your query based on some conditions.

For ex. I have a table named tbl_Listings which has lots of columns like city, address, postal code, state, listing price, bathroom, bedroom, etc.

Now i want to query all the records if user has not specified any filter. I want to filter city column only if the user has specified city name in the search filter.

To do that i have a class named "PredicateBuilder", by which i can dynamically create predicates and add them to main query.

Add the following class to your project.

PredicateBuilder.cs

public static class PredicateBuilder
{
    public static Expression> Make() { return null; }

    public static Expression> Make(this Expression> predicate)
    {
        return predicate;
    }

    public static Expression> Or(this Expression> expr, Expression> or)
    {
        if (expr == null) return or;
        var invokedExpr = Expression.Invoke(or, expr.Parameters.Cast());
        return Expression.Lambda>(Expression.Or(expr.Body, invokedExpr), expr.Parameters);
    }

    public static Expression> And(this Expression> expr, Expression> and)
    {
        if (expr == null) return and;
        var invokedExpr = Expression.Invoke(and, expr.Parameters.Cast());
        return Expression.Lambda>(Expression.And(expr.Body, invokedExpr), expr.Parameters);
    }
}

Now how to use this class? You just need to create an object of Predicate Class of your Table type (in my case tbl_Listings) and then add conditions to it.

//linq query
using (DataClassesDataContext db_context = new DataClassesDataContext())
        {
            //define predicate 
var predicate = PredicateBuilder.Make();
		
		//add predicate dynamically based on conditions
            if (city != "")
            {
                predicate = predicate.And(x => x.address_city == city);
            }
		

		//more predicates can be added dynamically here 

            var query = db_context.tbl_LISTINGs.Where(predicate);
         }

Like this you can apply filters on multiple columns dynamically.

Social Bookmarks

About the Author

Amit Panchal

Co-Founder,

Amitech Business Solutions

All Events

Textify

Comments (0)

Leave a comment

You are commenting as guest. Optional login below.

Cancel Submitting comment...