Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain OR clauses, with LINQ?

Tags:

c#

linq

I've got a scenario where I need to build a SQL query, using LINQ, that includes a variable amount of OR clauses. I'm writing a function that will build the query based on some input. The function definition looks something similar to ...

function BuildQuery(ICollection<ColumnsThatNeedToBeTrue> columns)
{
  ...
}

So, I'm given a collection of columns that I need to check for true, and the check needs to use OR clauses.

If the columns array contains A and B, I'd need the query to check if column A is true OR column B is true.

If the columns array contains A, B and C, I'd need to query and check if A OR B OR C are true.

I don't know how to do this all within a single Where, because I don't know of a way to progressively tack on additional || clauses. I'm not sure how I'd include additional OR checks in the below, based on the input array.

var query = entities.Where(m => m.A == true || m.B == true ...)

I cannot chain Where functions, each for their own column check, because it builds that query using AND clauses and I need OR.

Is there a way to build out a query like this, using LINQ?

like image 513
Ryan Avatar asked Mar 23 '16 18:03

Ryan


1 Answers

You can use the PredicateBuilder to chain or conditions.

var predicate = PredicateBuilder.False<SomeEntity>();

predicate = predicate.Or (p => p.A == true);
if(something)
   predicate = predicate.Or (p => p.B == true);

var query = entities.AsExpandable().Where (predicate); //AsExpandable() for EF
like image 52
Magnus Avatar answered Sep 19 '22 14:09

Magnus