Using the Take and Skip Keyword to reduce the number of records fetched in the Query

Hi,

One of the nicest things LINQ makes easy is paging. LINQ seems to de basic paging query out of the box. Paging is well built in LINQ and is very very easy to be used.

With LINQ we no longer have to right those complex logic just to create paging effect. The two mainly keyword mainly used for paging in LINQ framework are Take and Skip.

The Take keyword is used to decide how many records are to be fetched. A simple example of the Take keyword is provided below.

List<Customer> customers = GetCustomerList();
 
    var first3Customers = (
                from c in customers

                select new {c.CustomerID, c.CustomerName} )
                .Take(4);

Here we are taking the first 4 customer for the list provided.

we can also use the where clause to narrow down the list first and then take 4 of them.

    var first3Customers = (
                from c in customers
               where c.Region == "Kol"

                select new {c.CustomerID, c.CustomerName} )
                .Take(4);

But what if we want to get the the data between 4th and 8th record. In this case we use the skip keyword to skip the number of records(from top) we don’t want. Here is the example of using the Skip keyword.

    var first3Customers = (
                from c in customers
               where c.Region == "Kol"

                select new {c.CustomerID, c.CustomerName} )
                .Skip(3).Take(4);

here we are skipping the first three records and then getting the next four records. These techniques can be very useful when working with large set of data.

Vikram

Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 10/1/2007 8:44:58 AM

That was interesting

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2008 Vikram Lakhotia