Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking for null in lambda expression - linq

I am attempting to write an expression for an advanced search. However, I need to check if each property is null, otherwise an error will be thrown.

I have included the expression without the null checking below.

The result is output using jQuery dataTables.

filteredPeople = unitOfWork.PeopleRepository.Get().Where(c =>
   IdSearchable && c.personID.ToString().Contains(param.sSearch.ToLower())
   || surnameSearchable && c.Surname.ToLower().Contains(param.sSearch.ToLower())
   || firstNameSearchable && c.FirstName.ToLower().Contains(param.sSearch.ToLower())
   || genderSearchable && c.Gender.ToLower().Contains(param.sSearch.ToLower())
));
like image 267
jjc99 Avatar asked Feb 18 '23 04:02

jjc99


2 Answers

Try below, I basically wrapped all your individual conditional checks inside brackets to further aid both readability and to make sure you don't get any weird results with the compilers interpretation of that huge logic.

filteredPeople = unitOfWork.PeopleRepository.Get()
                .Where(c => (IdSearchable
                        && c.personID != null
                        && c.personID.ToString().Contains(param.sSearch.ToLower()))
                    || (surnameSearchable 
                        && c.Surname != null
                        && c.Surname.ToLower().Contains(param.sSearch.ToLower()))
                    || (firstNameSearchable 
                        && c.FirstName != null
                        && c.FirstName.ToLower().Contains(param.sSearch.ToLower()))
                    || (genderSearchable 
                        && c.Gender != null
                        && c.Gender.ToLower().Contains(param.sSearch.ToLower())));
like image 64
mattytommo Avatar answered Feb 27 '23 22:02

mattytommo


Try this:

filteredPeople = unitOfWork.PeopleRepository.Get()
                .Where(c => (IdSearchable
                     && c.personID != null
                     && c.personID.ToString().Contains(param.sSearch.ToLower()))
                   ||
                     ....

From MSDN

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

like image 21
Hamlet Hakobyan Avatar answered Feb 27 '23 22:02

Hamlet Hakobyan