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?
A single query expression may have multiple where clauses.
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.
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.
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
Use the following:
var q = MyTable;
q = q.Where(
t => (condition1 && t.Field1 == value1) || (condition2 && t.Field2 > t.Field3));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With