Using Take and skip keyword to filter records in LINQ

Posted by vik20000in on ASP.net Weblogs See other posts from ASP.net Weblogs or by vik20000in
Published on Wed, 07 Apr 2010 03:36:00 GMT Indexed on 2010/04/07 3:43 UTC
Read the original article Hit count: 570

In LINQ we can use the take keyword to filter out the number of records that we want to retrieve from the query. Let’s say we want to retrieve only the first 5 records for the list or array then we can use the following query

    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    var first3Numbers = numbers.Take(3);

The TAKE keyword can also be easily applied to list of object in the following way.

var first3WAOrders = (

        from cust in customers

        from order in cust.Orders

        select cust ) .Take(3);

[Note in the query above we are using the order clause so that the data is first ordered based on the orders field and then the first 3 records are taken.

In both the above example we have been able to filter out data based on the number of records we want to fetch. But in both the cases we were fetching the records from the very beginning. But there can be some requirements whereby we want to fetch the records after skipping some of the records like in paging.

For this purpose LINQ has provided us with the skip method which skips the number of records passed as parameter in the result set.

int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var allButFirst4Numbers = numbers.Skip(4);

The SKIP keyword can also be easily applied to list of object in the following way.

var first3WAOrders = (

        from cust in customers

        from order in cust.Orders

        select cust ).Skip(3);

 

Vikram

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about ASP.NET