Using Dynamic LINQ for Sorting

I found this a while ago about using dynamic LINQ in your code.  This really works well with the ASP.NET GridView (and other data bound controls) where sorting is supported.  Because, when a column header is clicked, the Sorting event fires with the details of the sort.  The event argument contains the field being sorted in string form (it's actually the name of the column stored in the column setup).

Because LINQ is strongly-typed, Dynamic LINQ allows a string name to be provided, which uses reflection to parse against the underlying type, and pass in the field that correponds to the SortExpression parameter.  In this way, Dynamic LINQ allows sorting without a huge if..else statement in the Sorting event handler.  It works really easily.

Use the following for sorting:

protected void grid_Sorting(object sender, GridViewSortEventArgs e)
    var dataSource = this.GetDataSource();
    dataSource = dataSource.OrderBy(e.SortExpression + " " + e.SortDirection.ToString().ToLower());


The order by statement using dynamic LINQ takes a string for the column name, but it also parses the text to look for an ascending or descending statement (I made it lower case because I saw it looked for lowercase text, and I didn't see that it lowered the text automatically).

Published Tuesday, June 03, 2008 11:14 PM by bmains
Filed under:


# Link Listing - June 4, 2008

Thursday, June 05, 2008 6:39 AM by Christopher Steen

MSBuild DevSource Article: Automation with MSBuild [Via: Steve ] WPF The Missing .NET #4: Cue Banner...

# Link Listing - June 4, 2008

Thursday, June 05, 2008 6:39 AM by Christopher Steen

Link Listing - June 4, 2008