this question has answer here:
- second linq filter multiple conditions 2 answers
i trying filter multiple attribute database. filtering 3 attributes. may empty or key in combination. have tried code, working fine when filtered in 3 steps,
ienumerable<employee> itemslist = _db.employees.asenumerable().where(e => e.role == 2).orderbydescending(e => e.employeeid); if (!string.isnullorempty(searchkeybyname)) { itemslist = itemslist.where(e => e.firstname.tolower().startswith(searchkeybyname.trim().tolower()) || e.lastname.tolower().startswith(searchkeybyname.trim().tolower()) || (e.firstname + " " + e.lastname).tolower().startswith(searchkeybyname.trim().tolower())); viewbag.search_fullname = searchkeybyname; } if (!string.isnullorempty(searchkeybydepartment)) { itemslist = itemslist.where(e => e.department.departmenttitle.tolower().startswith(searchkeybydepartment.trim().tolower())); viewbag.search_department = searchkeybydepartment; } if (!string.isnullorempty(searchkeybydesignation)) { itemslist = itemslist.where(e => e.designation.tolower().startswith(searchkeybydesignation.trim().tolower())); viewbag.search_designation = searchkeybydesignation; }
but want minimize 3 if condition linq, have tried 1 of using code
ienumerable<employee> itemslist2 = (from e in _db.employees.asenumerable() e.role == 2 (!string.isnullorempty(searchkeybyname) && (e.firstname.trim().tolower().startswith(searchkeybyname.trim().tolower()) || e.lastname.tolower().startswith(searchkeybyname.trim().tolower()) || (e.firstname + " " + e.lastname).tolower().startswith(searchkeybyname.trim().tolower()))) select e).orderbydescending(e => e.employeeid);
but filtering result being null/empty. 1st 1 working well. mention that, search key may empty, need peek values when key provided take key findings one.
the problem &&
; requiring searchkeybyname
not empty/null using that. filter should keep records if searchkeybyname
null or missing or use in search otherwise: searchkeybyname.isnullorempty() || (rest of it)
. in case, can simplify out using null coalescing, since every string starts empty string:
var itemslist2 = e in _db.employees let loweredsearch = (searchkeybyname ?? "").trim().tolower() e.role == 2 && ( (e.firstname + " " + e.lastname).tolower().startswith(loweredsearch) || e.lastname.tolower().startswith(loweredsearch) ) orderby e.employeeid descending select e;
but more efficient:
var itemslist2 = e in _db.employees let loweredsearch = (searchkeybyname ?? "").trim().tolower() e.role == 2 && ( loweredsearch == string.empty || (e.firstname + " " + e.lastname).tolower().startswith(loweredsearch) || e.lastname.tolower().startswith(loweredsearch) ) orderby e.employeeid descending select e;
Comments
Post a Comment