简体   繁体   中英

Which is a better linq query? .Where(crit).FirstOrDefault() or .Where(someCrit).FirstOrDefault(someOtherCrit)?

Looking to do a bit of refactoring... Using NHibernate I have this query currently

 public Widget FindByCode(string code)
 {
  return 
             _session
                 .Query<Widget>()
                 .Where(w => !w.IsDeleted)
                 .FirstOrDefault(w => w.Code == code);
  }

I was thinking of using this

public Widget FindByCode(string code)
 {
  return 
             _session
                 .Query<Widget>()
                 .Where(w => !w.IsDeleted && w.Code == code)
                 .FirstOrDefault();
  }

Is either one any better than the other? Any tips, links, or code is always appreciated. Cheers!

It seems confusing to me to split the predicate into two chunks. I'd keep the "filtering" code in one place and either put it all in .Where (your second example) or all in .FirstOrDefault . The latter option is more concise and uses fewer operators, so is generally ideal.

In linq2objects or linq2sql you can write just a FirstOrDefault like this:

public Widget FindByCode(string code)
 {
  return 
             _session
                 .Query<Widget>()
                 .FirstOrDefault(w => !w.IsDeleted && w.Code == code);
  }

Not sure about NHibernate, but but probably works. And you can always check the generated sql with NHProf, or regular sql profiler.

The second one is better since it will only do one projection based on both criterias. The first one will do a first projection based on the first criteria and then apply a second projection based on the second criteria. I would recommend using the second approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM