SkipLast Method
public static IEnumerable<TSource> SkipLast<TSource>(this IEnumerable<TSource> source, int count)
Bypasses a specified number of elements at the end of a sequence and then returns the remaining elements.
Returns
An IEnumerable<TSource>
that contains the elements that follow the omitted elements at the end of the input sequence. If count
is equal to or greater than the count of elements in source
, an empty IEnumerable<TSource>
is returned.
Remarks
- This method performs a deferred execution. The values of
source
andcount
are not validated until the result of this method is enumerated. - Negative values of
count
are treated as zero. - If the source sequence is empty, an empty sequence is returned.
- The
SkipLast
method works by first counting the total number of elements in the source sequence. Then, it returns all elements except for the lastcount
elements. - This method is the opposite of the
TakeLast
method.
Example
// Sample usage of SkipLast
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Skip the last 3 elements
var skipped = numbers.SkipLast(3);
// The 'skipped' sequence will contain { 1, 2, 3, 4, 5, 6, 7 }
foreach (var number in skipped)
{
Console.WriteLine(number);
}
// Example with an empty sequence
int[] emptyNumbers = { };
var skippedFromEmpty = emptyNumbers.SkipLast(2); // Result is an empty sequence
// Example with count greater than sequence length
var skippedTooMany = numbers.SkipLast(15); // Result is an empty sequence
// Example with negative count
var skippedNegative = numbers.SkipLast(-5); // Treated as SkipLast(0), returns all elements
Parameters
Name | Description |
---|---|
source |
An IEnumerable<TSource> to return elements from. |
count |
The number of elements to skip from the end of the sequence. |
Type Parameters
Name | Description |
---|---|
TSource |
The type of the elements of source . |