Given a collection, is there a way to get the last N elements of that collection? If there isn’t a method in the framework, what would be the best way to write an extension method to do this?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This approach preserves item order without a dependency on any sorting, and has broad compatibility across several LINQ providers.
It is important to take care not to call
Skipwith a negative number. Some providers, such as the Entity Framework, will produce an ArgumentException when presented with a negative argument. The call toMath.Maxavoids this neatly.The class below has all of the essentials for extension methods, which are: a static class, a static method, and use of the
thiskeyword.A brief note on performance:
Because the call to
Count()can cause enumeration of certain data structures, this approach has the risk of causing two passes over the data. This isn’t really a problem with most enumerables; in fact, optimizations exist already for Lists, Arrays, and even EF queries to evaluate theCount()operation in O(1) time.If, however, you must use a forward-only enumerable and would like to avoid making two passes, consider a one-pass algorithm like Lasse V. Karlsen or Mark Byers describe. Both of these approaches use a temporary buffer to hold items while enumerating, which are yielded once the end of the collection is found.