Using C# LINQ - A Practical Overview

player_one
5,176 views

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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.Collections.Generic;
using System.Linq;
namespace MultipleValue1
{
public static class Count1
{
// Return all words in the sequence between "start" (inclusive)
// and "end" (non-inclusive)
// For example, if given { "One", "start", "more", "end", "thing" } ...
// this method should return { "start", "more" }
public static IEnumerable<string> GetStartThroughEnd(IEnumerable<string> words)
{
// Uncomment:
// return words.???();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content