Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Methods - Extract multiple elements

In the previous lesson, we learned about Take() and Skip(), both of which accept an integer parameter. Each of these methods also have a variant that utilizes a delegate method to determine which elements will be taken or skipped.

TakeWhile(<predicate>) method

TakeWhile() behaves similarly to the Take() method except that instead of taking the first n elements of a sequence, it "takes" all of the initial elements of a sequence that meet the criteria specified by the predicate, and stops on the first element that doesn't meet the criteria. It then returns a new sequence containing all the "taken" elements.

The predicate is passed into TakeWhile() as a delegate method that takes a single parameter of type T (where T is the data type of the elements in the IEnumerable<T> sequence) and returns a bool indicating whether or not the passed-in element should be "taken".

List<int> ints = new List<int> { 1, 2, 4, 8, 4, 2, 1 };
// Will contain { 1, 2, 4 }
IEnumerable<int> result = ints.TakeWhile(theInt => theInt < 5);

SkipWhile(<predicate>) method

Just as Skip() is the spiritual opposite of Take(), SkipWhile() is the opposite of TakeWhile(). SkipWhile() "skips" the initial elements of a sequence that meet the criteria specified by the predicate and returns a new sequence containing the first element that doesn't meet the criteria as well as any elements that follow.

Again, the predicate is provided as a delegate method that takes a single element of type T and returns a bool indicating whether or not the passed-in element should be "skipped".

List<int> ints = new List<int> { 1, 2, 4, 8, 4, 2, 1 };
// Will contain { 4, 8, 4, 2, 1 }
IEnumerable<int> result = ints.SkipWhile(theInt => theInt != 4);

Exercise

In this exercise, make the GetStartThroughEnd() method return all the words from the provided sequence that occur between the words "start" (inclusive) and "end" (non-inclusive).

TakeWhile and SkipWhile Exercise
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content