Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 425
Massive Boisson Avatar asked Nov 09 '10 16:11

Massive Boisson


People also ask

Is LINQ faster than foreach?

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.

What is the difference between select and where in LINQ?

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.

Is LINQ faster than SQL?

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.


3 Answers

PredicateBuilder is the perfect solution for your problem. It allows you to keep adding individual "AND" as well as "OR" statements together.

like image 61
Ocelot20 Avatar answered Oct 18 '22 08:10

Ocelot20


You could do something like:

var query = from x in context.Xs
        where
          (x.X == 1) ||
          (x.Y == 2) ||
          (x.Z == "3")
        select x;
like image 36
Faizan S. Avatar answered Oct 18 '22 07:10

Faizan S.


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.

like image 24
Justin Niessner Avatar answered Oct 18 '22 08:10

Justin Niessner