6

Why do the ordinary laws in the evaluation of Boolean expression do not fit into...

 2 years ago
source link: https://www.codesd.com/item/why-do-the-ordinary-laws-in-the-evaluation-of-boolean-expression-do-not-fit-into-linq.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Why do the ordinary laws in the evaluation of Boolean expression do not fit into LINQ?

advertisements

In such a code:

if (insuranceNumberSearch == null
     ? true
     : ei.InsuranceNumber.Contains(insuranceNumberSearch.Trim()))
   doSomething();

where insuranceNumberSearch is null, remaining expression is not null while in following code:

var q = from ei in session.Linq<EmployeeInsurance>()
        where insuranceNumberSearch == null
                ? true
                : ei.InsuranceNumber.Contains(insuranceNumberSearch.Trim())
        select ei;

all section of expression is evaluated regardless of insuranceNumberSearch is null or is not null.

I'm using LINQ to NHibernate

UPDATE:

Unfortunately I have put the first snippet wrong. The correct is:

if (insuranceNumberSearch == null || (insuranceNumberSearch != null && ei.InsuranceNumber.Contains(insuranceNumberSearch.Trim()))
doSomething();

bool b1 = insuranceNumberSearch == null ? true : ei.InsuranceNumber.Contains(insuranceNumberSearch.Trim());
if (b1)
doSomething();

In both of above when insuranceNumberSearch is null, remaining expressions are not evaluated any more. If such a behavior does not exists, insuranceNumberSearch.Trim() will cause a reference object is null exception. Sadly LINQ (or maybe LINQ-to-NHibernate) does not obey such a nice behavior and evaluate all of expression even when insuranceNumberSearch is null and results in error.

UPDATE 2: I found a similar question: The || (or) Operator in Linq with C#


Beat me, but wth wouldn't you use

if (
     (insuranceNumberSearch == null) ||
     ei.InsuranceNumber.Contains(insuranceNumberSearch.Trim()))
  doSomething();

in your statement, be it in the LINQ expression or not?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK