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

These LINQ methods can be used to extract multiple elements from an IEnumerable<T> sequence. Each method in this chapter provides a different means of defining the criteria determining which sequence elements to remove and which elements to keep.

NOTE: Throughout this chapter, I state that a method "returns a sequence". This is not technically true. The methods in this chapter return an IEnumerable<T>, which is a generator (or an iterator) that can provide a sequence on demand. The difference is subtle, and can often be ignored, but there are some situations where the distinction is important. These special cases will be discussed in more detail in the Advanced Topics course.

Take() method

The Take() method extracts the first n elements (where n is a parameter to the method) from the beginning of the target sequence and returns a new sequence containing only the elements taken.

List<bool> bools = new List<bool> { true, false, true, true, false };
// Will contain { true, false, true }
IEnumerable<bool> result = bools.Take(3);

Skip() method

The Skip() method can be thought of as the exact opposite of the Take() method. Where the Take() method, returns a sequence containing the first n elements of the target sequence, the Skip() method "skips" over the first n elements in the sequence and returns a new sequence containing the remaining elements after the first n elements.

List<bool> bools = new List<bool> { true, false, true, true, false };
// Will contain { true, true, false }
IEnumerable<bool> result = bools.Skip(2);

Exercise

In this exercise, make the GetThirdFourthFifthItems() method return the 3rd, 4th, and 5th elements of the provided sequence.

Take and Skip Exercise
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.Collections.Generic;
using System.Linq;
namespace MultipleValue1
{
public static class SkipTake1
{
// Return the 3rd, 4th, and 5th items of the provided sequence.
public static IEnumerable<string> GetThirdFourthFifthItems(
IEnumerable<string> words)
{
// Uncomment:
// return words.???();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content