Yesterday, I was reading Efficient Paging in SQL Server 2005 post by Justin Etheredge, then in the comments I found Kevin Hazzard pointing to his Efficient LINQ to SQL custom paging approach. I liked his way, which reflects Justin's method which I already seen before but never apply it. I think it is more efficient than my method I provided in an earlier post. And if you googled about custom paging with LINQ to SQL you'll find few more implementation.
Today, I'm updating my method and provide the same sample I made last month with Kevin's method. I made an extension method to IQueryable Interface and called it KavinPage. You can view a demo here
Here is the code for the Extension Method:
1: public static IQueryable<T> KevinPage<T, TResult>(this IQueryable<T> obj, int page, int pageSize, System.Linq.Expressions.Expression<Func<T, TResult>> keySelector, bool asc, out int rowsCount)
3: rowsCount = obj.Count();
4: if (asc)
6: return obj.OrderBy(keySelector).Skip(page * pageSize).Take(pageSize);
10: return obj.OrderByDescending(keySelector).Skip(page * pageSize).Take(pageSize);
It is all about Extension Methods and how to use them to build SQL Queries. You can return for Kevin's post for detailed explanation. Also you can return to my previous post about this subject for more details about how to put it all together to build Paging ASP.NET ListView using LINQ to SQL and ObjectDataSource.
Download the updated sample.