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
An IEnumerable<T>.
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().
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With