c# - Which is better checking of null types or using Any() in LINQ? -


i have 2 codes , have know better use. i'm thinking same. if i'm not mistaken, first has 1 call database, however, don't know if checking of repo != null right.

(1)

var repo = repository   .query()   .where(ur => ur.customerid == customerid)   .singleordefault();  if (repo != null) {     // update repo     repo.name = "name here"; } else {     // code } 

(2)

var repo = repository   .query()   .any(ur => ur.customerid == customerid);  if (repo) {     var result = repository       .query()       .where(ur => ur.customerid == customerid)       .single();      result.name = "name here"; } else {     // code } 

the second option finds 1 element 2 times. here

repository   .query()   .any(ur => ur.customerid == customerid) 

and here

repository   .query()   .where(ur => ur.customerid == customerid)   .single() 

and first option finds 1 time. reason choosing first option. , also, can make code better:

var repo = repository   .query()   .where(ur => ur.customerid == customerid)   .singleordefault(); 

just write

var repo = repository   .query()   .singleordefault(ur => ur.customerid == customerid); 

and advice future: use any() when want check fact has element in query, don't need element.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -