C# .NET: Take a List of Any Object and Paginate It

11/22/2013 10:29:40 PM

Take a list of any object that is not paginated and paginate it. This could be done when retrieving data from a database. If you return all rows from a table and populate a list, this will allow you to paginate that list.

*Pagination should be done on the database side but this still is a useful function.

//using statements
using System;
using System.Collections.Generic;

.....

public static List<T> GetPaginatedList<T>(IList<T> source, int page, int recordsPerPage)
{
	int startIndex = 0;
	int endIndex = 0;

	if (page <= 0)
	{
		page = 1;
	}

	if (recordsPerPage <= 0)
	{
		startIndex = 0;
		endIndex = Int32.MaxValue;
	}
	else
	{
		startIndex = (page * recordsPerPage) - recordsPerPage;
		endIndex = (page * recordsPerPage) - 1;
	}

	//Cap end Index
	if (endIndex > source.Count - 1)
	{
		endIndex = source.Count - 1;
	}

	List<T> newList = new List<T>();
	for (int x = startIndex; x <= endIndex; x++)
	{
		newList.Add((T)source[x]);
	}

	return newList;
}

....

//use of function

//fill non-paginated list
List<MyObject> nonPaginatedList = SomeSpecialFunctionThatFillsInTheList();

//create paginated list
int page = 1;
int recordsPerPage = 10;

List<MyObject> paginatedList = GetPaginatedList(nonPaginatedList, page, recordsPerPage);