public static IEnumerable<TSource> TakeLast<TSource>(this IEnumerable<TSource> source, int count)
Returns elements from the end of a sequence.
Name | Type | Description |
---|---|---|
source |
IEnumerable<TSource> |
An IEnumerable<TSource> to return elements from the end of. |
count |
int |
The number of elements to return from the end of the sequence. |
An IEnumerable<TSource>
that contains the elements from the end of the input sequence that have the specified count.
This method has no effect if count
is less than or equal to zero. If count
is greater than or equal to the number of elements in source
, the entire source
sequence is returned.
The source sequence is iterated only once.
ArgumentNullException
: source
is null.ArgumentOutOfRangeException
: count
is negative.using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // Get the last 3 elements IEnumerable<int> lastThree = numbers.TakeLast(3); Console.WriteLine("Last 3 elements:"); foreach (int number in lastThree) { Console.Write(number + " "); } // Output: 8 9 10 Console.WriteLine(); // Get the last 0 elements IEnumerable<int> lastZero = numbers.TakeLast(0); Console.WriteLine("Last 0 elements:"); foreach (int number in lastZero) { Console.Write(number + " "); } // Output: (empty line) Console.WriteLine(); // Get the last 15 elements (more than available) IEnumerable<int> lastFifteen = numbers.TakeLast(15); Console.WriteLine("Last 15 elements:"); foreach (int number in lastFifteen) { Console.Write(number + " "); } // Output: 1 2 3 4 5 6 7 8 9 10 } }