472,338 Members | 1,826 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 472,338 developers and data experts.

Dynamic LINQ Where Clauses -- PredicateBuilder

Curtis Rutland
3,256 Expert 2GB
This isn't a full-blown article, just a quickie. But I couldn't pass up the opportunity to share this insight with people, because it made my coding life sooooooo much easier.

http://www.albahari.com/nutshell/predicatebuilder.aspx

Its usefulness is situational, but I found it most valuable when I was building a searching application. I had no idea which parameters a user might include in their search. I didn't want to string-build a select statement, because I'd already created my LINQ to SQL classes, and I didn't want to do dynamic LINQ because to me the whole point of LINQ is type safety and IntelliSense.

So I found the PredicateBuilder. My favorite part of this is that it's not some big library that you have to download and include. It's a few lines of code that you can just paste into your own project:

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4. using System.Collections.Generic;
  5.  
  6. public static class PredicateBuilder
  7. {
  8.   public static Expression<Func<T, bool>> True<T> ()  { return f => true;  }
  9.   public static Expression<Func<T, bool>> False<T> () { return f => false; }
  10.  
  11.   public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
  12.                                                       Expression<Func<T, bool>> expr2)
  13.   {
  14.     var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
  15.     return Expression.Lambda<Func<T, bool>>
  16.           (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
  17.   }
  18.  
  19.   public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
  20.                                                        Expression<Func<T, bool>> expr2)
  21.   {
  22.     var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
  23.     return Expression.Lambda<Func<T, bool>>
  24.           (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
  25.   }
  26. }
Add a namespace and dump that into your project, and you can use it.

The article explains how to use it better than I could. I did find one odd behavior: using foreach loops.

You would normally do this:
Expand|Select|Wrap|Line Numbers
  1. foreach(string s in stringCollection)
  2. {
  3.     whereClause = whereClause.Or(p => p.SomeString == s);
  4. }
However, for some reason, it seems to copy the pointer to "s" or something, and you end up with all the Or statements using the last value of s. To fix this, you do:
Expand|Select|Wrap|Line Numbers
  1. foreach(string s in stringCollection)
  2. {
  3.     string temp = s;
  4.     whereClause = whereClause.Or(p => p.SomeString == temp);
  5. }
Other than that, it works great.
May 12 '10 #1
0 25109

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: codingholic | last post by:
I have a table like the following: CREATE TABLE Customers ( CustomerCode varchar(20) not null, Surname varchar(60) not null, Firstname...
4
by: BeSharp | last post by:
I recently stumbled across a pretty interesting LINQ to SQL question and wonder, whether anybody might have an answer. (I'm doing quite some...
15
by: EDBrian | last post by:
My problem is this. Our clients create different fields they want to collect and we allow them build dynamic filters, reports etc... We run some...
0
by: EDBrian | last post by:
Problem: We enable our clients to create custom fields they wish to collect. We want to use Dynamic LINQ to query this table (Just one). My initial...
9
by: =?Utf-8?B?RXZlcnQ=?= | last post by:
In my (Windows Forms) project I am using strongly typed datatables. Now I am trying to convert my 'rowfilter/group by' query logic to Linq. Most...
1
by: Lacutas | last post by:
Hi I'm having some problems getting a dynamic LINQ query to work on my DataSet. The idea is that a user selects certain criteria, and then the...
2
by: Joey | last post by:
I am querying a DataSet with LINQ. I am running into a problem when trying to construct my query because in the "from" clause I do not know the...
4
by: =?Utf-8?B?TWlrZSBDb2xsaW5z?= | last post by:
I am trying to set up a dynamic search using linq. I believe the syntax is correct, but cannot confirm it because when I try to cast my Session...
2
by: giddy | last post by:
hi, Yes its a design question again. =) If I have something like: class Person { //functions: static Person GetAllPersons(); static Person...
0
by: Jay Douglas | last post by:
Hello, I've found some posts on creating dynamic WHERE clauses in LINQ to SQL using predicate builders and extending lamda expressions. One...
0
by: concettolabs | last post by:
In today's business world, businesses are increasingly turning to PowerApps to develop custom business applications. PowerApps is a powerful tool...
0
better678
by: better678 | last post by:
Question: Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct? Answer: Java is an object-oriented...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.