Friday, August 05, 2011

Paging in LINQ

Implementation of paging  with help from ROW_COUNT() of SQL in LINQ :

Implementation:

public static IEnumerable<T> Paging<T>(int rowCount, int pageId, IQueryable<T> query)

{

    return  query       

        .Skip((pageId - 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");

   Paging(10, 1,query )

       .ToList()

       .ForEach(

        item => Console.WriteLine(item.ID + ": " + item.Name)

        );

    Console.WriteLine("Attempt 2");

    Paging(5, 2, query)

        .ToList()

        .ForEach(

        item => Console.WriteLine(item.ID + ": " + item.Name)

        );

}

Class:

public class Foo

{

    public int ID { get; set; }

    public string Name { get; set; }

}

 


And now as extension!

Enjoy!

kick it on DotNetKicks.com

No comments: