Take the 2-minute tour ×

Following this example from http://www.albahari.com/nutshell/predicatebuilder.aspx

IQueryable<Product> SearchProducts (params string[] keywords)
  var predicate = PredicateBuilder.False<Product>();

  foreach (string keyword in keywords)
    string temp = keyword;
  return dataContext.Products.Where (predicate);

I have a similiar requirement except that firstly I have to do an AND query and secondly , unlike the above example, I have a bunch of field names and a value to search in each of them. The field names and the values both are unknown till the user passes them through. I ended up doing something like the code below which works but obviously is very tightly coupled.

 IEnumerable<someClass> qry = context.someClass;
 var pb = PredicateBuilder.True<someClass>();

 foreach (customClass rule in Filters)

                switch ( rule.field)
                    case "FirstName":
                            pb = pb.And(p=>p.FirstName.Contains(rule.data));
                    case "LastName":
                            pb = pb.And(p=>p.LastName.Contains(rule.data));
                    case "City":
                           pb = pb.And(p=>p.City.Contains(rule.data));


            return qry;

As can be seen from above the Rule class has a field and data property. What would be ideal is if I could dynamically create the predicatebuilder , something like

filterClause = "p=>p." + rule.field + ".Contains(" + rule.data + ")";

pb = pb.And(filterClause);


Thanks in advance for any inputs

share|improve this question
thats look fine to me, are you getting any error with it?? –  Gopesh Sharma Jan 23 '13 at 6:00
No I am looking for a better way to achieve the same result..if it is possible that is –  shai Jan 23 '13 at 7:42
Did you mean the second code bit with filterClause looks fine to you ? Well the predicatebuilder only accepts function arguments so the string argument doesnt work. Throws an error –  shai Jan 23 '13 at 7:50
You may want to look at this answer - stackoverflow.com/a/2297519/201648. It looks like Dynamic Linq could be the answer to your question - weblogs.asp.net/scottgu/archive/2008/01/07/… –  Aaron Newton Jan 24 '13 at 2:10
I'm encountering exactly the same problem. –  Lei Yang Jul 29 '13 at 2:40

Your Answer



Browse other questions tagged or ask your own question.