Hi there,
Trying something with Linq / Lambda's, but have no idea where to search.
I'm working on some simple sorting in an ASP.net GridView. Here's some sample code:
IQueryable<User> query = (from c in users select c).AsQueryable<User>();
if (isAscending)
{
switch (e.SortExpression)
{
case "Name":
query.OrderBy(c => c.Name);
break;
default:
break;
}
}
else
{
switch (e.SortExpression)
{
case "Name":
query.OrderByDescending(c => c.Name);
break;
default:
break;
}
}
grid.DataSource = query.ToList();
grid.DataBind();
I am, however, unsatisfied with the code as it is very sensitive to errors and requires lots of duplicated code. I'm hoping to solve this using Lambda expressions instead, but I have no idea how. Here's what I would like to go to:
IQueryable<User> query = (from c in users select c).AsQueryable<User>();
var param = null;
switch (e.SortExpression)
{
case "Name":
param = (c => c.Name);
break;
default:
break;
}
if (isAscending)
{
query.OrderBy(param);
}
else
{
query.OrderByDescending(param);
}
grid.DataSource = query.ToList();
grid.DataBind();
Could anyone please help me? Thanks!