Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 661
Andrew Harry Avatar asked Nov 21 '09 09:11

Andrew Harry


People also ask

What is the LINQ equivalent to the SQL IN operator?

An IEnumerable<T>.

How do I return a single value from a list using LINQ?

var fruit = ListOfFruits. FirstOrDefault(x => x.Name == "Apple"); if (fruit != null) { return fruit.ID; } return 0; This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First().

How use contains in LINQ query?

LINQ Contains operator is used to check whether an element is available in sequence (collection) or not. Contains operator comes under Quantifier Operators category in LINQ Query Operators. Below is the syntax of Contains operator.

What is select in LINQ C#?

The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.


1 Answers

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);
like image 87
Johannes Rudolph Avatar answered Oct 07 '22 03:10

Johannes Rudolph