Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to objects Predicate Builder

What is the best way to do a conditional query using linq to objects(not linq to sql).

Currently I am using the Predicate builder found here http://www.albahari.com/nutshell/predicatebuilder.aspx and passing the compiled predicate to the IEnumerable.Where and it seems to work nicely.

Example code of what I want to solve:

eg I have this

 string keyword1 = "Test1";
 string keyword2 = "Test3";

        IEnumerable<TestObject> tests = new List<TestObject>()
                                     {
                                         new TestObject() {Name1 = "Test1", Name2 = "Test1"},
                                         new TestObject() {Name1 = "Test2", Name2 = "Test2"},
                                         new TestObject() {Name1 = "Test3", Name2 = "Test3"},

                                     };

        if (!String.IsNullOrEmpty(keyword1) && String.IsNullOrEmpty(keyword2))
            tests = tests.Where(e => e.Name1.Contains(keyword1));
        else if (!String.IsNullOrEmpty(keyword2) && !String.IsNullOrEmpty(keyword1))
            tests = tests.Where(e => e.Name2.Contains(keyword2) || e.Name1.Contains(keyword1));

        return tests.ToList();
like image 457
kwiri Avatar asked Aug 17 '11 14:08

kwiri


1 Answers

Just change PredicateBuilder to use delegates instead of expression trees and use lambdas to build the results:

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

  public static Func<T, bool> Or<T>(this Func<T, bool> expr1,
                                     Func<T, bool> expr2)
  {
      return t => expr1(t) || expr2(t);
  }

  public static Func<T, bool> And<T>(this Func<T, bool> expr1,
                                     Func<T, bool> expr2)
  {
      return t => expr1(t) && expr2(t);
  }
}
like image 148
Jon Skeet Avatar answered Oct 22 '22 21:10

Jon Skeet