tags:

views:

452

answers:

3

How do you page through a collection in LINQ given that you have a startIndex and a count?

+18  A: 

It is very simple with the Skip and Take extension methods.

var query = from i in ideas
select i;

var paggedCollection = query.Skip(startIndex).Take(count);
Nick Berardi
Did you ask a question... and then answer it to get + votes for the question and answer? You answered this 2 minutes after asking.
Timothy Khouri
I believe that it's OK to do something like this. He might have an answer but maybe he wants to see what other people can come up with as well.
Outlaw Programmer
This was originally posted during the first day of the beta period of StackOverflow, thus the 66 for the article ID. I was testing the system, for Jeff. Plus it seemed like useful information instead of the usual test crap that sometimes comes out of beta testing.
Nick Berardi
+6  A: 

A few months back I wrote a blog post about Fluent Interfaces and LINQ which used an Extension Method on IQueryable and another class to provide the following natural way of paginating a LINQ collection.

var query = from i in ideas
            select i;
var pagedCollection = query.InPagesOf(10);
var pageOfIdeas = pagedCollection.Page(2);

You can get the code from the MSDN Code Gallery Page: Pipelines, Filters, Fluent API and LINQ to SQL.

Wolfbyte
+1  A: 

You might want to take a look at Rob Conery's PagedList.

Eric Haskins