I use LINQ to create my where clause like so:
var query = from x in context.Xs
select x;
if (y == ...)
{
query = query.Where(x => x.Y == 1);
}
I have bunch of these "if .... where" statements. The issue I have is that all of those wheres join where clauses using AND but I need all my where clauses to use OR. Is there an easy way to port this code into where OR code? Or even what is the easiest way to do this with OR?
Thanks.
LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code.
In case of Select it you can map to an IEnumerable of a new structure. Where() works as an filter to the IEnumerable, it will return the result on the basis of the where clause.
Sql is faster than Linq. Its simple: if I m executing a sql query directly its a one way process whereas if I m using linq, first its been converted to sql query and then its executed.
PredicateBuilder is the perfect solution for your problem. It allows you to keep adding individual "AND" as well as "OR" statements together.
You could do something like:
var query = from x in context.Xs
where
(x.X == 1) ||
(x.Y == 2) ||
(x.Z == "3")
select x;
I would suggest using Expression Trees to build your query dynamically:
(MSDN) How to: Use Expression Trees to Build Dynamic Queries
You could also use a PredicateBuilder
(which does something similar under the hood) to build the Predicate dynamically and then pass the final Predicate to the Where method.
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