I have this simple piece of code
public ActionResult ListToGrid(string field, string direction)
{
_model.MyList = _repo.List();
}
To sort开发者_开发问答, I can do this :
_model.MyList = _employeeService.List().OrderBy(x => x.FirstName).ToList<Employee>();
But I'd like use "as field" the name receive (field) in argument and the direction received too.
Thanks,
You could use reflection, but that would be rather slow. The most efficient would be declare a delegate to use in the sort, and assign a function depending on the string:
Func<Employee,string> order;
switch (field) {
case "FirstName": order = x => x.FristName;
case "LastName": order = x => x.LastName;
}
For the direction I think it's best to simply 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>();
Search for sites that talk about dynamic LINQ expressions. For example, this one shows how to do dynamic sorting:
http://blogs.sftsrc.com/stuart/archive/2009/02/19/130.aspx
You can then also choose whether to call OrderBy
or OrderByDescending
depending on the direction parameter.
精彩评论