Compose LINQ-to-SQL predicates into a single predicate

后端 未结 2 862
感情败类
感情败类 2021-02-09 23:02

(An earlier question, Recursively (?) compose LINQ predicates into a single predicate, is similar to this but I actually asked the wrong question... the solution there satisfied

2条回答
  •  一向
    一向 (楼主)
    2021-02-09 23:59

    You can use the PredicateBuilder class

    IQueryable SearchCustomers (params string[] keywords)
    {
      var predicate = PredicateBuilder.False();
    
      foreach (string keyword in keywords)
      {
        // Note that you *must* declare a variable inside the loop
        // otherwise all your lambdas end up referencing whatever
        // the value of "keyword" is when they're finally executed.
        string temp = keyword;
        predicate = predicate.Or (p => p.Forenames.Contains (temp));
      }
      return dataContext.Customers.Where (predicate);
    }
    

    (that's actually the example from the PredicateBuilder page, I just adapted it to your case...)


    EDIT:

    Actually I misread your question, and my example above only covers a part of the solution... The following method should do what you want :

    IQueryable SearchCustomers (string[] forenameKeyWords, string[] surnameKeywords)
    {
        var predicate = PredicateBuilder.True();
    
        var forenamePredicate = PredicateBuilder.False();
        foreach (string keyword in forenameKeyWords)
        {
          string temp = keyword;
          forenamePredicate = forenamePredicate.Or (p => p.Forenames.Contains (temp));
        }
        predicate = PredicateBuilder.And(forenamePredicate);
    
        var surnamePredicate = PredicateBuilder.False();
        foreach (string keyword in surnameKeyWords)
        {
          string temp = keyword;
          surnamePredicate = surnamePredicate.Or (p => p.Surnames.Contains (temp));
        }
        predicate = PredicateBuilder.And(surnamePredicate);
    
        return dataContext.Customers.Where(predicate);
    }
    

    You can use it like that:

    var query = SearchCustomers(
        new[] { "keyword1", "keyword2" },
        new[] { "keyword3", "keyword4" });
    
    foreach (var Customer in query)
    {
        ...
    }
    

提交回复
热议问题