c# - 'Then By' usage with different number of criterias -
i writing c# program allows user specify sorting criterias. example, user can sort "servicename", or add several other criterias "ishd" or "isgood". ask is, want use '.then by' statement user determines how many times need write it.
is there way can flexibility on number of criteria depending on switch/case block? e.g
list.orderby(t => t.name) list.orderby(t => t.ishd).thenby(t => t.name) list.orderby(t => t.isgood).thenby(t => t.name).thenby(t => t.ishd) also order of these criteria chosen user.
you can use generic method:
public list<t> sortby<t>(list<t> list, params func<t, object>[] selectors) { var ordered = list.orderby(selectors[0]); (int = 1; < selectors.count(); i++) { ordered= ordered.thenby(selectors[i]); } return ordered.tolist(); } run it:
sortby(list, x=>x.name, x=>x.ishd, x=>x.isgood) which do:
list.orderby(x=>x.name).thenby(x=>x.ishd).thenby(x=>x.isgood) can improved checking if selectors passed
Comments
Post a Comment