c# - Search function LINQ. Use checkbox values as parameters -
i have search function tales 7 parameters , 6 of them checkbox values. bools shown down below. have problem datetime search. if user check box if run serach function date not null in database. code @ moment. feedback how improve code better performance , code structure.
public list<invoice> getallinvoicesbysearch(int merchant, long buyer, bool send, bool paid, bool firstreminder, bool secondreminder, bool invoiceclaim) { var sendvalue = new invoicestatus(); var paidvalue = new invoicestatus(); var firstremind = new datetime(); var secondremind = new datetime(); if (buyer <= 0) { return null; } if (send) { sendvalue = invoicestatus.sent; } if (paid) { paidvalue = invoicestatus.paid; } if (firstreminder) { firstremind = datetime.now; } if (secondreminder) { secondremind = datetime.now; } return context.invoices.where( => i.installationid == merchant && i.buyer.msisdn == buyer || i.status == sendvalue || i.status == paidvalue || i.firstreminderdate == firstremind || i.secondreminderdate == secondremind).tolist(); } so problem datetime @ moment correctly. suggestions on how solve problem , improve code?
you better off using predicatebuilder , converting extension method this:
public static class extensionmethods { public static iqueryable<invoice> search(this iqueryable<invoice> src, int merchant, long buyer, bool send, bool paid, bool firstreminder, bool secondreminder, bool invoiceclaim) { var predicate = predicatebuilder.false<invoice>(); var sendvalue = new invoicestatus(); var paidvalue = new invoicestatus(); var firstremind = new datetime(); var secondremind = new datetime(); if (buyer <= 0) { return src.where(predicate); } predicate=predicate.or(i=>i.installationid == merchant && i.buyer.msisdn == buyer); if (send) { predicate=predicate.or(i=>i.status == invoicestatus.sent); } if (paid) { predicate=predicate.or(i=>i.status == invoicestatus.paid); } if (firstreminder) { predicate=predicate.or(i=>i.firstreminderdate == datetime.today); } if (secondreminder) { predicate=predicate.or(i=>i.secondreminderdate == datetime.today); } return src.where(predicate); } } also, if understand code correctly, invoicestatus should either enum, or @ least, invoicestatus.sent , invoicestatus.paid should marked being static. reference so:
context.invoices.search(...).orderby(...)...
it make further manipulation easier if need sorting, paging, filtering beyond original searching.
Comments
Post a Comment