If I want to append a AND statement to my query, I can do:
query = query.Where(obj=>obj.Id == id);
if(name.HasValue)
query = query.Where(obj=>obj.Name == name);
and it will give me:
query.Where(obj=>obj.Id == id && obj.Name == name)
How can I append a OR statement that will result in:
query.Where(obj=>obj.Id == id || obj.Name == name)
You can't do it natively. However, you can use PredicateBuilder to compose the query before you run it, and it supports ORs.
var predicate = PredicateBuilder.False<Product>();
predicate = predicate.Or (obj=>obj.Id == id);
if(name.HasValue) predicate = predicate.Or (obj=>obj.Name == name);
return query.Where(predicate);
Simply this if I'm not missing something:
query.Where(obj=>obj.Id == id || (obj.Name == name && name.HasValue))
You might want to read this question (my question...) and answer for more complicated scenarios:
How to filter IEnumerable based on an entity input parameter
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