Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

LINQ and Dynamic Predicate Construction at Runtime

, 13 Aug 2008
Illustrating a multi-predicate injection pattern now possible with the new features of C# 3.0.
LINQDynamicPredicate_demo.zip
LINQDynamicSearchDemo
App_Data
Global.asax
NorthwindDB.dbml
NorthwindDB.dbml.layout
Properties
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

// Note: This file is not written by me. It's from the "C# 3.5 in a Nutshell" book website, here: http://www.albahari.com/nutshell/predicatebuilder.html

namespace LINQDynamicSearchDemo {
    public static class PredicateBuilder {
        public static Expression<Func<T, bool>> True<T>() { return f => true; }
        public static Expression<Func<T, bool>> False<T>() { return f => false; }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                            Expression<Func<T, bool>> expr2) {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);
        }

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
                                                             Expression<Func<T, bool>> expr2) {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
        }
    }
}

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)

Share

About the Author

dave.dolan

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140905.1 | Last Updated 14 Aug 2008
Article Copyright 2008 by dave.dolan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid