BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

LINQ
.NET 3.5+

LINQ Partitioning with Indexes

The LINQ partitioning operators allow the first elements of a sequence to be extracted, or skipped so that all other elements are returned. When using TakeWhile and SkipWhile, the index of each item can be included in the predicate.

Partitioning

Language-Integrated Query (LINQ) includes four partitioning operators that each split a sequence into two parts. The "Take" operators return the first segment of the sequence and the "Skip" operators return the second part. Each of these operators has two versions. The standard Take and Skip methods include an integer parameter that determines how many items in the source sequence should be extracted or ignored. TakeWhile and SkipWhile let you return a variable number of items according to a predicate, usually supplied as a lambda expression. Items are taken, or skipped, until the predicate returns false.

In some situations you may wish to use the index of the items in a sequence as part of the predicate in TakeWhile and SkipWhile. The following two sections explain how.

TakeWhile with Indexes

The basic version of TakeWhile uses a Func delegate that acts upon each item in the sequence and returns a Boolean result. Whilst the result is true, the items from the sequence are extracted. You can extend the predicate with a second parameter that represents the zero-based index of the sequence.

This can be seen in the sample code below. Here the value from the source array is represented by "v" in the lambda expression. "i" provides the index of the item. The resultant sequence contains the items from the start of the sequence where the value is less than or equal to the index number. The first item for which this is not true is the value 8 at index 6, which marks the end of the results.

var values = new int[] { 0, 1, 1, 2, 3, 5, 8, 13, 21 };
var taken = values.TakeWhile((v, i) => v <= i);         // 0, 1, 1, 2, 3, 5

SkipWhile with Indexes

The SkipWhile predicate can be used with the same two parameters when the index number is to be used. The following sample code uses the same lambda expression as the previous example. This returns the remaining three items.

var values = new int[] { 0, 1, 1, 2, 3, 5, 8, 13, 21 };
var taken = values.SkipWhile((v, i) => v <= i);         // 8, 13, 21
27 June 2011