Filters a sequence by taking the first n
elements.
public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count);
Name | Type | Description |
---|---|---|
source |
IEnumerable<TSource> |
An IEnumerable<T> to return elements from. |
count |
int |
The number of elements to return. |
An IEnumerable<TSource>
that contains the first count
elements from the input sequence.
Type | Condition |
---|---|
ArgumentNullException |
source is null. |
ArgumentOutOfRangeException |
count is negative. |
The following code example demonstrates how to use the Take
method to retrieve the first three elements of an array.
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
int[] numbers = { 5, 4, 2, 3, 6, 7, 9, 8, 10, 1, 1, 1 };
// Get the first 3 elements
IEnumerable<int> firstThree = numbers.Take(3);
Console.WriteLine("First three elements:");
foreach (int num in firstThree)
{
Console.Write(num + " ");
}
// Output: 5 4 2
}
}
If you specify zero for the count
, an empty sequence is returned.
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
string[] words = { "apple", "banana", "cherry" };
// Take zero elements
IEnumerable<string> zeroElements = words.Take(0);
Console.WriteLine("Sequence with zero elements:");
foreach (string word in zeroElements)
{
Console.Write(word + " ");
}
// Output: (empty line)
}
}
The Take
extension method is used to limit the number of elements returned from a sequence. It is particularly useful when you only need a subset of data, such as the top N items or the first few results from a query.
If the number of elements in the source sequence is less than the specified count
, the entire sequence is returned.
The Take
method operates lazily. It does not return a new list or array immediately. Instead, it returns an iterator that yields the elements one by one as they are requested.