1

I have a table which has hundreds of columns (like FirstName and LastName).

All this data is displayed as a GridView with listing. I've made use of the SortCommand event which has the e.SortExpression, but I can't fathom how to use it in an OrderBy function since after inputting a lambda expression. IntelliSense shows me all the hundreds of columns instead of the one I need - which I only have at run-time.

How do I use the Func<TSource, TKey> selector the OrderBy functions expects from me to let it know that the string e.SortExpression is the column that needs to be sorted?

Example of what I essentially mean:

private void dataGrid_SortCommand(object source, DataGridSortCommandEventArgs e)
{
    var users = new UsersEntities().UsersTable.OrderBy(x => "x."+e.SortExpression);
    FillDataGrid(users); 
}

Update: I've come to understand that the way in which I'm looking to accomplish this is using Expression trees, and I'm hoping someone can provide the exact solution.

Update 2: I've found the solution here. Turns out my question was a duplicate and to add to that, badly worded. Thanks to everyone.

And I've also just noticed that ken's offered pretty damning evidence that I should use dynamic linq. I'll consider doing so in the future, but I couldn't help but notice how fun it is to experiment with Expression trees rather than rely on libraries to do them for me. At this stage, as I'm still new to Expression trees this is a perfect opportunity to utilize them.

4

2 回答 2

1

You can use dynamic linq That would allow you to do an OrderBy based on a string.

Edit

See my comment. Using dynamic linq, your solution could be as easy as:

var users = new UsersEntities().UsersTable.OrderBy(e.SortExpression);
于 2013-04-11T13:12:36.223 回答
0

You can dynamically create LINQ expressions easily as long as only logical ANDs are involved in where clauses. Simply repeat the Where clause!

// Filter
var query = new UsersEntities().UsersTable.Select(x => x);
if (!String.IsNullOrEmpty(nameFilter) {
    query = query.Where(x => x.Name == nameFilter);
}
if (!String.IsNullOrEmpty(zipFilter) {
    query = query.Where(x => x.Zip == zipFilter);
}

// Sorting
switch (sortField)
{
    case "Name":
        query = query.OrderBy(x => x.Name);
        break;
    case "Zip":
        query = query.OrderBy(x => x.Zip);
        break;
}

You could also create an expression tree dynamically, but this is not very obvious.

于 2013-04-11T14:15:56.840 回答