C# – checking for null in lambda expression – linq

asp.net-mvccjquery-datatableslinq

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())
));

Best Answer

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())));