Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a compound "or" clause in Linq?

Tags:

c#

linq

If you're adding "and" conditions to a Linq query, it's easy to do it like so:

var q = MyTable;
if (condition1)
  q = q.Where(t => t.Field1 == value1);
if (condition2)
  q = q.Where(t => t.Field2 > t.Field3);
// etc.

Is there any clever way of doing the same thing, when you want to add "or" conditions?

like image 748
Shaul Behr Avatar asked Jun 19 '11 09:06

Shaul Behr


People also ask

Can we use multiple where clause in LINQ?

A single query expression may have multiple where clauses.

What is GroupBy in LINQ?

In LINQ, the GroupBy operator is used to groupin the list/collection items based on the specified value of the key, and it returns a collection of IGrouping<key, Values>. The GroupBy method in LINQ is the same as the SQL group by statement.

What is GroupBy in C#?

GroupBy() Method in C# The GroupBy() is an extension method that returns a group of elements from the given collection based on some key value. The following is our array − int[] arr = { 2, 30, 45, 60, 70 }; Now, we will use GroupBy() to group the elements smaller than 50 − arr.


2 Answers

You can use a PredicateBuilder and use it to build an Or based expression:

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

 predicate = predicate.Or (t => t.Field1 == value1);
 predicate = predicate.Or (t => t.Field2 > t.Field3);

 q = q.Where (predicate);

You can read more about it here: http://www.albahari.com/nutshell/predicatebuilder.aspx

Replace the Product in PredicateBuilder.False<Product>() with your queried object.

Note that you start from a False predicate as you want to use Or. If You'd want an And predicate, Yuo should start from a True

like image 116
Variant Avatar answered Oct 13 '22 13:10

Variant


Use the following:

var q = MyTable;
q = q.Where(
     t => (condition1 && t.Field1 == value1) || (condition2 && t.Field2 > t.Field3));
like image 45
Akram Shahda Avatar answered Oct 13 '22 13:10

Akram Shahda