Tuesday, October 1, 2013

Implementing Paging in a Generic List using LINQ

It's quite common of users to bind their Generic List to an ASP.NET control. However if the list is huge, you may need to implement Paging functionality. Here's a simple way to do implement Paging functionality using LINQ


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class LINQ : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        List<Employee> empList = new List<Employee>();
        empList.Add(new Employee() { ID = 1, FName = "John",  DOB = DateTime.Parse("12/11/1971")});
        empList.Add(new Employee() { ID = 2, FName = "Mary",  DOB = DateTime.Parse("01/17/1961")});
        empList.Add(new Employee() { ID = 3, FName = "Amber", DOB = DateTime.Parse("12/23/1971")});
        empList.Add(new Employee() { ID = 4, FName = "Kathy", DOB = DateTime.Parse("11/15/1976")});
        empList.Add(new Employee() { ID = 5, FName = "Lena",  DOB = DateTime.Parse("05/11/1978")});
 
        var records = from emp in empList
                      select emp;
        var pgNo = 1;
        var pgRec = 2;
        records = records.Skip((pgNo - 1) * pgRec).Take(pgRec);
 
        foreach (var r in records)
        {
            Console.WriteLine(r.FName);
        }
 
    }
 
    class Employee
    {
        public int ID { get; set; }
        public string FName { get; set; }
        public DateTime DOB { get; set; }
    }
 
}

0 comments:

Post a Comment