Home >Backend Development >C++ >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!