Linq to objects Predicate Builder

拈花ヽ惹草 提交于 2019-12-17 10:51:15

问题


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();

回答1:


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);
  }
}


来源:https://stackoverflow.com/questions/7094930/linq-to-objects-predicate-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!