Andrew Harry
Andrew Harry

Reputation: 13909

Linq To Sql 'Where Or' operator

I need to create a query which checks if a field (string) contains one or more words supplied at run time.

Basically I need to be able to ask a WhereOr question. This seems like it should be a common issue when dealing with LinqToSql.

I found the following reference but can't make sense out of it - and have no idea how to use it in my project.

i've tried the following loop:

        var query = from d in context.Domains select d;
        for (int i = 0; i < words.Length; i++)
        {
            query = query.Where(d => d.Name.Contains(words[i]));
        }

but this builds a SQL query with WHERE AND Clauses NOT Where OR

Upvotes: 9

Views: 4635

Answers (1)

Johannes Rudolph
Johannes Rudolph

Reputation: 35721

I use PredicateBuilder for such things.

The predicate construction looks like this:

     var query = from d in context.Domains select d;
     var predicate = PredicateBuilder<Domains>.False();

     for (int i = 0; i < words.Length; i++)
        {
            predicate = predicate.Or(d => d.Name.Contains(words[i]));
        }
    query = query.Where(predicate);

Upvotes: 17

Related Questions