Reputation: 51917
I have a gridview with several columns, 3 of which I'd like to sort. The source for the data is held in the session.
protected void MyGridHistorySort(object sender, GridViewSortEventArgs e)
{
var TheColumn = (e.SortExpression).ToString();
TheDataHistory = (List<ViewDataHistoryModel>)Session["SessionDataHistory"];
var test = "data.DataDate";
var NewDataSource = from data in TheDataHistory
orderby test
select data;
MyGridHistory.DataSource = NewDataSource;
MyGridHistory.DataBind();
DataDate is a valid column in the list but the orderby statement doesn't work. Ideally, I'd like it to sort with the variable TheColumn by writing something like test = "data."+TheColum; and then add a sort direction based on a boolean. I looked at the OrderBy extension method NewDataSource.OrderBy(test); but that doesn't work either.
What am I missing to make my code work?
Thanks.
Upvotes: 1
Views: 5805
Reputation: 14400
Copy paste the code in my answer and change the Select to OrderBy and dynamic to T ;) How to make the position of a LINQ Query SELECT variable
Upvotes: 0
Reputation: 29032
It looks like you need to have
var NewDataSource = from data in TheDataHistory
orderby data.DataDate
select data;
Since the orderby clause takes a property name. The clause doesn't parse the string to determine what to order by like Dynamic Queryable does.
Or, in the case of sorting on multiple fields, I would use
var NewDataSource = from data in TheDataHistory
select data;
switch(fieldToSortOn)
{
case "field1":
NewDataSource = NewDataSource.OrderBy(x => x.Field1);
break;
case "field2":
NewDataSource = NewDataSource.OrderBy(x => x.Field2);
break;
...
}
If you are really bent on just using a string to sort this, then I would totally recommend the Dynamic Queryable library. I've been using it and it's perfect for what I've been doing lately (with some added support for DateTime? objects)
Then you can do things like
NewDataSource = NewDataSource.DynamicOrderBy("ID DESC, Name DESC, Price ASC");
Love this library!
Upvotes: 1
Reputation: 6771
You could use Dynamic Linq for this expression:
string sortExpression = "ContactName DESC";
var x1 = context
.Customers
.OrderBy(sortExpression);
Upvotes: 0