DanScan
DanScan

Reputation: 901

Retrieve paged results using Linq

I want to get items 50-100 back from a result set in linq. How do I do that?

Situation: I get back an index of the last item of the last result set. I want to then grab the next 50. I do not have the ID of the last result only its index number.

Upvotes: 0

Views: 137

Answers (2)

Corey
Corey

Reputation: 16564

LINQ is based on the concept of one-way enumeration, so queries all start at the beginning. To implement paging you'll have to use the Skip and Take extensions to isolate the items you're interested in:

int pageSize = 50;
// 0-based page number
int pageNum = 2;
var pageContent = myCollection.Skip(pageSize * pageNum).Take(pageSize);

Of course this just sets up an IEnumerable<T> that, when enumerated, will step through myCollection 100 times, then start returning data for 50 steps before closing.

Which is fine if you're working on something that can be enumerated multiple times, but not if you're working with a source that will only enumerate once. But then you can't realistically implement paging on that sort of enumeration anyway, you need an intermediate storage for at least that portion of it that you've already consumed.

In LINQ to SQL this will result in a query that attempts to select only the 50 records you've asked for, which from memory is going to be based taking numSkip + numTake records, reversing the sort order, taking numTake records and reversing again. Depending on the sort order you've set up and the size of the numbers involved this could be a much more expensive operation than simply pulling a bunch of data back and filtering it in memory.

Upvotes: 2

Ronan Thibaudau
Ronan Thibaudau

Reputation: 3603

You order it by Something, else you really can't

So it would be Something like

mycontext.mytable
    .OrderBy(item=>.item.PropertyYouWantToOrderBy)
    .Skip(HowManyYouWantToSkip)
    .Take(50);

Upvotes: 2

Related Questions