LINQ and pagination [duplicate]

2020-01-26 04:10发布

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

3条回答
走好不送
2楼-- · 2020-01-26 04:49

.Skip and .Take extension methods could be used:

var result = (from c in Customers
              select new 
              {
                  c.City,
                  c.ContactName
              }
              ).Skip(5).Take(5);
查看更多
Fickle 薄情
3楼-- · 2020-01-26 04:54

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)
查看更多
再贱就再见
4楼-- · 2020-01-26 04:56

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)
查看更多
登录 后发表回答