Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Linq for paging a generic collection?

I've got a System.Generic.Collections.List(Of MyCustomClass) type object.

Given integer varaibles pagesize and pagenumber, how can I query only any single page of MyCustomClass objects?

like image 722
Zack Peterson Avatar asked Aug 21 '08 21:08

Zack Peterson


People also ask

Which LINQ methods should you use to implement pagination?

We can implement the paging using the Linq Skip and Take method.

What collections can LINQ be used with?

You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API.

What is LINQ when and how would you use it?

LINQ is a data querying API that provides querying capabilities to . NET languages with a syntax similar to a SQL. LINQ queries use C# collections to return data. LINQ in C# is used to work with data access from sources such as objects, data sets, SQL Server, and XML.


1 Answers

If you have your linq-query that contains all the rows you want to display, this code can be used:

var pageNum = 3;
var pageSize = 20;
query = query.Skip((pageNum - 1) * pageSize).Take(pageSize);

You can also make an extension method on the object to be able to write

query.Page(2,50)

to get the first 50 records of page 2. If that is want you want, the information is on the solid code blog.

like image 111
Espo Avatar answered Oct 07 '22 17:10

Espo