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
Release: 2025-01-05 04:21:38
Original
469 people have browsed it

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));
Copy after login

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));
    }
}
Copy after login

Usage:

collection.TakeLast(5);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template