Take
Take()
returns the first specified number of elements. It acts upon an IEnumerable
sequence. It returns another IEnumerable
sequence containing the specified elements.
Take
returns the first elements of an IEnumerable
. And TakeWhile()
, a more complex form of Take()
, accepts the first elements while a predicate method returns true.
We use the Take()
method. Take()
is a method in the System.Linq
namespace that allows you to get the first several elements from a sequence. It receives an element count.
Take()
call returns the first 2 elements in the List
. This could display the 2 oldest, first elements.Take()
call is chained after a Reverse
string
call. It operates on the result of Reverse
.Take()
call uses the top 1000 elements, which is nonsense as there are not 1000 elements in the List
.using System; using System.Collections.Generic; using System.Linq; List<string> list = new List<string>(); list.Add("cat"); list.Add("dog"); list.Add("programmer"); // Part 1: get first 2 elements. var first = list.Take(2); foreach (string s in first) { Console.WriteLine(s); } Console.WriteLine(); // Part 2: get last 2 elements reversed. var last = list.Reverse<string>().Take(2); foreach (string s in last) { Console.WriteLine(s); } Console.WriteLine(); // Part 3: get first 1000 elements. var all = list.Take(1000); foreach (string s in all) { Console.WriteLine(s); } Console.WriteLine();cat dog programmer dog cat dog programmer
TakeWhile
This method returns elements while a Predicate
matches. The Predicate
returns true or false. When it returns false, TakeWhile
returns.
TakeWhile
operates from the beginning of an IEnumerable
collection. It can be called on the result of another method like Skip
.TakeWhile
extension method is invoked. It returns the first 3 odd numbers, but not the even numbers at the end.using System; using System.Linq; // Part 1: create array with 5 numbers. int[] values = { 1, 3, 5, 8, 10 }; // Part 2: take all non-even (odd) numbers. var result = values.TakeWhile(item => item % 2 != 0); foreach (int value in result) { Console.WriteLine(value); }1 3 5
Skip
and Take
We can combine Skip
with Take
(and SkipWhile
, TakeWhile
). In this example we indicate elements we want to avoid based on a numeric pattern.
SkipWhile
to skip some lower-value elements, and then call TakeWhile
to take some until a limit is reached.using System; using System.Linq; int[] values = { 10, 20, 30, 40, 50, 60 }; // Use SkipWhile and TakeWhile together. var result = values.SkipWhile(v => v < 30).TakeWhile(v => v < 50); foreach (var value in result) { Console.WriteLine("RESULT: {0}", value); }RESULT: 30 RESULT: 40
LINQ methods are often used together. Skip
is useful when paired with Take
. It allows you to avoid the first several elements in the sequence.
Take()
gets elements from a collection. Also, we saw Reverse
with Take
, and how to use extension methods. TakeWhile
accepts a predicate and is more powerful.