Implementation:
public static IEnumerable<T> Paging<T>(this IQueryable<T> query,int rowCount, int pageIndex)
{
return query
.Skip((pageIndex - 1) * rowCount)
.Take(rowCount);
}
Using:
private void TestMethod()
{
Random rnd = new Random();
List<Foo> fooList = new List<Foo>();
for (int i = 0; i < 20; i++)
{
fooList.Add(
new Foo
{
ID = rnd.Next(100),
Name = Membership.GeneratePassword(5, 0)
}
);
}
var query = fooList.OrderBy(item => item.ID).AsQueryable();
Console.WriteLine("Attempt 1");
query.Paging(10, 1)
.ToList()
.ForEach(
item => Console.WriteLine(item.ID + ": " + item.Name)
);
Console.WriteLine("Attempt 2");
query.Paging(5, 2)
.ToList()
.ForEach(
item => Console.WriteLine(item.ID + ": " + item.Name)
);
}
Class:
public class Foo
{
public int ID { get; set; }
public string Name { get; set; }
}