views:

44

answers:

2

Here I have an arbitrary IEnumerable<T>. And I'd like to page it using a generic helper function instead of writing Skip/Take pairs every time. Here is my function:

IEnumerable<T> GetPagedResults<T>(IEnumerable<T> query, int pageIndex, int pageSize)
{
   return query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
}

And my code is:

result = GetPagedResults(query, 1, 10).ToList();

This produces a SELECT statement without TOP 10 keyword. But this code below produces the SELECT with it:

result = query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

What am I doing wrong in the function?

+3  A: 

I believe you need to change it to use IQueryable instead, in order to maintain the deferred execution. When you use IEnumerable, it will apply the extra functions (Skip, Take, etc) in memory after the base query is executed. However, using IQueryable will cause the additional methods to be included in the query being sent to the database.

Mike Mooney
Yes that seems to be the problem, thanks! I don't know why I stuck with IEnumerable instead.
ssg
I only know because I got caught by the exact same thing :)
Mike Mooney
+2  A: 

Try using IQueryable...

IQueryable<T> GetPagedResults<T>(IQueryable<T> query, 
                                 int pageIndex, 
                                 int pageSize)
{
    return query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
} 
Matthew Whited