Paging and Sorting Database Records for the Presentation Layer (and for general use...)

A very common feature, shared by many applications that show to the user grid with data drawn from the server, is paging and sorting.

 

A very elegant and easy way for paging is demonstrated in http://blogs.msdn.com/wriju/archive/2007/10/04/linq-to-sql-paging-data.aspx.

 

As for sorting, this may be more complex, because the OrderBy extension method looks like:

System.Linq.Expressions.Expression<Func<T, TResult>> keySelector

 

One very nice solution can be found in a CSharpSamples, which contains many and very useful samples of code. One of them is the DynamicQuery project, which shows how build Linq queries dynamically. This helps us in our case to pass to our method the column name to sort by (instead of the intimidating System.Linq.Expressions.Expression<Func<T, TResult>> keySelector).

 

A nice description of the DynamicQuery project can be found @: 

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx