开发者

sort gridview with dynamic linq

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.


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!


You could use Dynamic Linq for this expression:

string sortExpression = "ContactName DESC";     
var x1 = context     
    .Customers    
    .OrderBy(sortExpression);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜