49

We need to fetch data from a database using LINQ. We now need to implement pagination.

I suppose at a time we need to fetch 10 records at a time and when we click the Next button then it will fetch the next 10 records from db.

Please guide me with code. thanks

Nico
  • 12,493
  • 5
  • 42
  • 62
Mou
  • 15,673
  • 43
  • 156
  • 275

3 Answers3

124

I always use the following code:

public static class PagingExtensions
{
    //used by LINQ to SQL
    public static IQueryable<TSource> Page<TSource>(this IQueryable<TSource> source, int page, int pageSize)
    {
        return source.Skip((page - 1) * pageSize).Take(pageSize);
    }

    //used by LINQ
    public static IEnumerable<TSource> Page<TSource>(this IEnumerable<TSource> source, int page, int pageSize)
    {
        return source.Skip((page - 1) * pageSize).Take(pageSize);
    }

}

That is a static class, which you can include in your sources. After adding this class you can do the following:

MyQuery.Page(pageNumber, pageSize)
Wim Haanstra
  • 5,918
  • 5
  • 41
  • 57
  • 9
    Please note that in LINQ to SQL you must first sort the input. – Sal Jul 12 '17 at 19:52
  • 1
    Useful as common extension method. – Rahul Saxena Feb 26 '20 at 07:18
  • This only works if page 1 is your starting page. If you want to start with page number 0 for the first page, then remove the -1 from the page. And just do: return source.Skip(page * pageSize).Take(pageSize); – J-ho Jun 10 '21 at 06:22
  • this came very handy, thanks for posting the solution – Jozcar Feb 26 '22 at 18:10
  • @Sal your comment "Please note that in LINQ to SQL you must first sort the input" seems interesting. Could you please describe this in depth. I'm keen to know the reason. – Aԃιƚყα Gυɾαʋ Aug 25 '22 at 14:55
  • 1
    @AԃιƚყαGυɾαʋ This is why: https://stackoverflow.com/a/3437253/1458738 – Sal Aug 26 '22 at 04:18
29

The LINQ Take() function will limit how many items are taken. The Skip() function will ignore the first n items. Something like this might work:

myDataSource.Skip(pageSize * curPage).Take(pageSize)
dlev
  • 48,024
  • 5
  • 125
  • 132
16

.Skip and .Take extension methods could be used:

var result = (from c in Customers
              select new 
              {
                  c.City,
                  c.ContactName
              }
              ).Skip(5).Take(5);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928