c# - Order IList with field name in argument -


i have simple piece of code

public actionresult listtogrid(string field, string direction) {     _model.mylist = _repo.list(); } 

to sort, can :

_model.mylist = _employeeservice.list().orderby(x => x.firstname).tolist<employee>(); 

but i'd use "as field" name receive (field) in argument , direction received too.

thanks,

you use reflection, rather slow. efficient declare delegate use in sort, , assign function depending on string:

func<employee,string> order; switch (field) {    case "firstname": order = x => x.fristname;    case "lastname": order = x => x.lastname; } 

for direction think it's best use separate codes:

var list = _employeeservice.list(); ienumerable<employee> sorted; if (direction == "ascending") {    sorted = list.orderby(order); } else {    sorted = list.orderbydescending(order); } _model.list = sorted.tolist<employee>(); 

Comments

Popular posts from this blog

unicode - Are email addresses allowed to contain non-alphanumeric characters? -

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -