LINQ WHERE with OR
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.
You could do something like:
var query = from x in context.Xs
where
(x.X == 1) ||
(x.Y == 2) ||
(x.Z == "3")
select x;
PredicateBuilder is the perfect solution for your problem. It allows you to keep adding individual "AND" as well as "OR" statements together.
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.
精彩评论