Search code examples
entity-frameworklinqlinq-to-entities

Build LINQ query in a loop


I have a LINQ query (which will be executed against a DbContext), which I start off by building using some conditions I know of beforehand.

var r = from p in db.People
        where blah
        select p;

I then have a bunch of search conditions, provided as an array (string[]). If I wanted to do an AND, this is easy:

foreach (string s in searchParameters)
{
      r = from r1 in r
          where r1.field == s
          select r1;
}

However, I now have a need to use these parameters in an OR fashion. One solution is to do something like:

var results = new List<IEnumerable<RowType>>();
foreach (string s in searchParameters)
{
      var r2 = from r1 in r
          where r1.field == s
          select r1;
      results.Add(r2);
}

and then, at the end, do a UNION of all the entries in "results". But, this would translate to a much more needlessly complicated query on the DB, and also introduce potentially duplicate rows which I'd then need to de-dup.

Is there an easy as well as efficient way to achieve what I'm trying to do?

Thanks


Solution

  • you need to make use of PredicateBuilder, If i am getting correctly you are making single query and you need conditions in it

    IQueryable<Product> SearchProducts (params string[] keywords)
    {
      var predicate = PredicateBuilder.False<Product>();
    
      foreach (string keyword in keywords)
      {
        string temp = keyword;
        predicate = predicate.Or (p => p.Description.Contains (temp));
      }
      return dataContext.Products.Where (predicate);
    }
    

    Dynamically Composing Expression Predicates