tags:

views:

97

answers:

2

Hello,

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,

+1  A: 

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.

Eilon
+1  A: 

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>();
Guffa
Could you give an exemple, how use "order" with _model.MyList it's an IList<MyObject> .... thanks,
Kris-I
_model.MyList.OrderBy(order) returns an IEnumerable<MyObject>.
Guffa