11

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Massive Boisson
  • 1,617
  • 7
  • 22
  • 28
  • 2
    Possible duplicate of [Linq: β€œOr” equivalent of Where()](http://stackoverflow.com/questions/2101540/linq-or-equivalent-of-where). – rsenna Nov 09 '10 at 16:42

3 Answers3

8

You could do something like:

var query = from x in context.Xs
        where
          (x.X == 1) ||
          (x.Y == 2) ||
          (x.Z == "3")
        select x;
Faizan S.
  • 8,634
  • 8
  • 34
  • 63
7

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

Ocelot20
  • 10,510
  • 11
  • 55
  • 96
4

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.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536