How do I sort a DataTable on the client side using LINQ? (Server side sorting is not supported with my data store)
I was doing something like this which doesn’t work
IEnumerable<DataRow> dr = GetDataTableData().AsEnumerable();
if (sortDirection == "Ascending")
{
dr = dr.OrderBy(x => sortExpression);
}
else
{
dr = dr.OrderByDescending(x => sortExpression);
}
GridView1.DataSource = dr;
GridView1.DataBind();
But I dont see the gridview sorting at all, what am I missing here?
My guess is that sortExpression is a string that you are passing in to the method; You should be sorting on something in x. eg:
As Rory pointed out in the comments, you can just use x[sortExpression] in your case; If you were using objects instead of the DataRow, you could make a key selector expression and pass it in to OrderBy() instead; something like:
then your OrderBy would look like: