Search code examples
c#.netlinqlambdalinq-to-sql

Iterable disjunction in LINQ


Let's assume I have an IQueryable collection, and list of some strings.

I can build query this way:

foreach (var somestring in somestrings)
{
     collection = collection.Where(col=>col.Property.Contains(somestring);
}

which will produce following SQL query:

SELECT ...... FROM ..... WHERE 
(Property LIKE '%something1%') AND 
(Property LIKE '%something2%') AND 
(Property LIKE '%something3%')

Note, that WHERE clauses are connected with ANDs.

Is there way, to construct similar query, but connected with ORs ?


Solution

  • You can use a PredicateBuilder like this. See SO for more.

    Here you can connect queries with AND or OR.

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

    Sample taken from C# 7.0 in a Nutshell

    I've used this successfully when implementing custom search fields

    eg.

    [red blue] -> searches for red AND blue

    [red, blue] -> searches for red OR blue