Geeks With Blogs
Jeroen Bourdeaud'hui web application developer

Last, I needed a function to add paging. The first problem I had, was how to this.
A couple of seconds later, I allready had a solution to this problem: Linq

Skip and take will do the trick.

list<t>.Skip(_howManyRecordsDoYouWantToSkip).Take(_howManyRecordsDoYouWantToTake)

This won't crash if you pass one of both statements. It will just return the result.

source.Skip(startRowIndex).Take(pageSize)

I've created an extension method to use this function.

 VB


     Module LinqHelpers
        <System.Runtime.CompilerServices.Extension()> _
        Public Function Page(Of TSource)(ByVal source As IEnumerable(Of TSource), ByVal startRowIndex As Integer, ByVal pageSize As Integer) As IEnumerable(Of TSource)
            Return source.Skip(startRowIndex).Take(pageSize)
        End Function
    End Module


 C#


public static class LinqHelpers
{
    public static IEnumerable Page(this IEnumerable source, int startRowIndex, int pageSize)
    {
            return source.Skip(startRowIndex).Take(pageSize);
    }
}

 

Change IEnumerable to IQueryable if you want to use Linq to SQL.

Take care about the traffic, if you use large lists and add paging at runtime. You'd better select the rows you want to show! (IQueryable)

 

Posted on Tuesday, May 10, 2011 12:22 PM asp.net , C# , vb.net , Linq , Paging | Back to top


Comments on this post: Paging using Linq

# re: Paging using Linq
Requesting Gravatar...
There's a commonly used open source implementation of this. It even has MVC page helpers.

https://github.com/TroyGoode/PagedList/
Left by Ryan on May 10, 2011 10:11 PM

# re: Paging using Linq
Requesting Gravatar...
It's doing the same thing, so it doesn't matter. Great stuff
Left by Luigi on May 10, 2011 10:51 PM

Your comment:
 (will show your gravatar)


Copyright © Jeroen Bourdeaud'hui | Powered by: GeeksWithBlogs.net