Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ lambda expression append OR statement

Tags:

c#

linq

c#-3.0

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)
like image 639
James Avatar asked Jan 15 '23 23:01

James


2 Answers

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);
like image 77
Bobson Avatar answered Jan 25 '23 11:01

Bobson


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

like image 31
gdoron is supporting Monica Avatar answered Jan 25 '23 12:01

gdoron is supporting Monica