Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# lambda expression if condition inside a where

Tags:

c#

lambda

I have a scenario where I am using lambda expression to filter data by name, address and phone number. But when one property has no value then my filter considers where property is null and it give wrong results. Is there any option to remove a where condition out of three cases with a if condition if property is null. I mean is there any case to add where/check only for object where properties having values?

var filterCriteria ={
name: "abc",
address:"",
phone:""
}

var Details = _context.LogEntities
                    .Where(p => p.name == (filterCriteria.name))
                    .Where(p => p.address== (filterCriteria.address))
                    .Where(p => p.phone== (filterCriteria.phone))

                return Json(Details);
like image 631
Kurkula Avatar asked Aug 22 '26 07:08

Kurkula


1 Answers

If you still want to return records when the name, address, or phone are null then just check for null in the condition.

var Details = _context.LogEntities
                    .Where(p => p.name == null || p.name == (filterCriteria.name))
                    .Where(p => p.address == null || p.address == (filterCriteria.address))
                    .Where(p => p.phone == null || p.phone == (filterCriteria.phone))

                return Json(Details);
like image 67
Alex Wiese Avatar answered Aug 23 '26 19:08

Alex Wiese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!