.NET API Documentation

Microsoft

System.Linq.Enumerable.Take

Summary

Returns a specified number of contiguous elements from the start of a sequence.

Syntax

public static IEnumerable<TSource> Take<TSource>(
	IEnumerable<TSource> source,
	int count
);

Parameters

Name Description
source An IEnumerable<TSource> to return elements from.
count The maximum number of elements to return.

Returns

An IEnumerable<TSource> that contains the first count elements of the input sequence.

Exceptions

Exception Type Condition
ArgumentNullException source is null.
ArgumentOutOfRangeException count is negative.

Remarks

The Take extension method is typically used to limit the number of results returned from a LINQ query. It's particularly useful when dealing with large sequences where you only need a subset of the data.

If count is greater than or equal to the number of elements in source, the entire source sequence is returned.

If count is zero, an empty sequence is returned.

Examples

The following code example demonstrates how to use the Take method to retrieve the first 3 elements from an array.

using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main()
    {
        int[] numbers = { "one", "two", "three", "four", "five" };

        IEnumerable<string> firstThree = numbers.Take(3);

        Console.WriteLine("The first 3 elements are:");
        foreach (string number in firstThree)
        {
            Console.WriteLine(number);
        }
    }
}