TakeWhile and SkipWhile method in LINQ

 

In my last post I talked about how to use the take and the Skip keyword to filter out the number of records that we are fetching. But there is only problem with the take and skip statement. The problem lies in the dependency where by the number of records to be fetched has to be passed to it. Many a times the number of records to be fetched is also based on the query itself.

For example if we want to continue fetching records till a certain condition is met on the record set. Let’s say we want to fetch records from the array of number till we get 7. For this kind of query LINQ has exposed the TakeWhile Method.

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

    var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 7);

 

In the same way we can also use the SkipWhile statement. The skip while statement will skip all the records that do not match certain condition provided. In the example below we are skiping all those number which are not divisible by 3. Remember we could have done this with where clause also, but SkipWhile method can be useful in many other situation and hence the example and the keyword.

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

    var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0);

Vikram

1 Comment

Comments have been disabled for this content.