Home >Backend Development >C++ >How to Efficiently Get the Last N Elements of a Collection Using LINQ?

How to Efficiently Get the Last N Elements of a Collection Using LINQ?

Linda Hamilton
Linda HamiltonOriginal
2025-01-05 04:21:38465browse

How to Efficiently Get the Last N Elements of a Collection Using LINQ?

How to Retrieve the Last N Elements of a Collection Using LINQ

To obtain the last N elements of a collection, LINQ offers the efficient Skip() method. By combining it with a conditional statement via Math.Max(), we can avoid errors stemming from negative input.

collection.Skip(Math.Max(0, collection.Count() - N));

This approach preserves the original item order without resorting to sorting and is compatible with multiple LINQ providers.

For more flexibility, the provided extension method encapsulates the above logic:

public static class MiscExtensions
{
    public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> source, int N)
    {
        return source.Skip(Math.Max(0, source.Count() - N));
    }
}

Usage:

collection.TakeLast(5);

While the Count() call incurs an enumeration for certain data structures, optimizations exist for common ones like Lists and Arrays. For forward-only enumerables, alternative one-pass algorithms (e.g., by Lasse V. Karlsen or Mark Byers) avoid multiple passes over the data.

The above is the detailed content of How to Efficiently Get the Last N Elements of a Collection Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn