Click here to Skip to main content
12,457,938 members (48,876 online)
Click here to Skip to main content

Stats

133.7K views
1.9K downloads
85 bookmarked
Posted

LINQ and Dynamic Predicate Construction at Runtime

, 13 Aug 2008 CPOL
Illustrating a multi-predicate injection pattern now possible with the new features of C# 3.0.
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.

You may also be interested in...

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