.net - How to optimize my if else code c# -
i have code below:
tryupdatemodel(model); if (modelstate.isvalid && model.fullnameischecked == true && model.lookingfor == null) { model.contactlist = contactrepository.getall(filter: x => x.userid == user.id); model.contactlist.sort((x, y) => string.compare(x.fullname, y.fullname)); } else if (modelstate.isvalid && model.fullnameischecked == false && model.lookingfor == null) { model.contactlist = contactrepository.getall(filter: x => x.userid == user.id); model.contactlist.sort((x, y) => string.compare(x.email, y.email)); } else if (modelstate.isvalid && model.lookingfor != null && model.fullnameischecked == true) { model.contactlist = contactrepository.getall(filter: x => x.userid == user.id); model.contactlist = contactrepository.getall(filter: x => x.fullname.contains(model.lookingfor)); model.contactlist.orderby(f => f.fullname); } else if (modelstate.isvalid && model.lookingfor != null && model.fullnameischecked == false) { model.contactlist = contactrepository.getall(filter: x => x.userid == user.id); model.contactlist = contactrepository.getall(filter: x => x.email.contains(model.lookingfor)); model.contactlist.orderby(e => e.email); } else { model.contactlist = contactrepository.getall(filter: x => x.userid == user.id); }
i'm using .net mvc 5 razor engine, , code above make sorting operations. can optimize if else part of code? thing on mind use switch - case operator similarly. in advance
- i cant see use in code checking state
modelstate
no need compare bool in if condition, ie
if(true)
is same as
if(bool variable=true)
use
string.isnullorempty
checknull
tryupdatemodel(model); model.contactlist = contactrepository.getall(filter: x => x.userid == user.id); if( string.isnullorempty(model.lookingfor)) { if(model.fullnameischecked) { model.contactlist.sort((x, y) => string.compare(x.fullname, y.fullname)); } else { model.contactlist.sort((x, y) => string.compare(x.email, y.email)); } } else { if(model.fullnameischecked) { model.contactlist = contactrepository.getall(filter: x => x.fullname.contains(model.lookingfor)); model.contactlist.orderby(f => f.fullname); } else { model.contactlist = contactrepository.getall(filter: x => x.userid == user.id); model.contactlist = contactrepository.getall(filter: x => x.email.contains(model.lookingfor)); } }
Comments
Post a Comment