Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Take or skip some elements in the collection
The next two methods we discuss are
Take(numberOfElements)
andSkip(numberOfElements)
Take
returns the first n
elements:
var numbers = new [] { 1, 2, 3, 4, 5, 6 };
var result = numbers.Take(3); // 1, 2, 3
Skip
discards the first n
elements:
var numbers = new [] { 1, 2, 3, 4, 5, 6 };
var result = numbers.Skip(3); // 4, 5, 6
You can also combine the methods:
var numbers = new [] { 1, 2, 3, 4, 5, 6 };
var result = numbers.Skip(1).Take(3); // 2, 3, 4
This is NEW - Method Chaining!
Here we have to stop and deliberately walk through the last example again.
We just discovered a very powerful feature of LINQ: method chaining!
As the LINQ methods covered so far have the same type IEnumerable<T>
as input and output, we can call a LINQ method on the result of another LINQ method.
Here is what happens:
- The first call to
Skip
skips the first element and returns the succeeding elements. - The second call to
Take
retunrs the first three elements of the result ofSkip
.
var numbers = new [] { 1, 2, 3, 4, 5, 6 };
var result = numbers // 1, 2, 3, 4, 5, 6
.Skip(1) // 2, 3, 4, 5, 6
.Take(3); // 2, 3, 4
You can aply method chaining to any LINQ method. They are designed to work that way.
Method chaining example
Return the first two adults of a collection.
Where and Take
1
11
12
13
14
15
16
17
// {
public IEnumerable<Person> TakeFirstTwoAdults(IEnumerable<Person> people)
{
return people
.Where(p => p.Age >= 30)
.Take(2);
}
// {
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content