【问题标题】:Linq to objects Predicate BuilderLinq to objects 谓词生成器
【发布时间】:2011-08-17 23:01:06
【问题描述】:

使用 linq to objects(不是 linq to sql)进行条件查询的最佳方法是什么。

目前我正在使用在这里找到的谓词构建器http://www.albahari.com/nutshell/predicatebuilder.aspx 并将编译后的谓词传递给 IEnumerable.Where,它似乎工作得很好。

我要解决的示例代码:

我有这个

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

【问题讨论】:

    标签: c# linq-to-objects


    【解决方案1】:

    只需更改 PredicateBuilder 以使用委托而不是表达式树并使用 lambdas 来构建结果:

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

    【讨论】:

    • 行得通,谢谢乔恩,是否有任何性能问题可能是由于构建这样的查询而不是使用长 if 语句手动执行而导致的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多