Given that you have an IList<T>
(assuming from your prose), then you can use a for
loop to grab the last n
pretty easily. This will still be lazily evaluated like much of LINQ -
public static IEnumerable<T> LastN<T>(this IList<T> list, int n)
{
if (list == null)
{
throw new ArgumentNullException("list");
}
if (list.Count - n < 0)
{
n = list.Count;
}
for (var i = list.Count - n; i < list.Count; i++)
{
yield return list[i];
}
}
// use
var tail50 = myList.LastN(50);
This will also well suited for an ICollection<T>
.
There are some collection types that implement ICollection<T>
, such as LinkedList<T>
, that if you know about their concrete types, there may be more efficient ways to accomplish what you're needing. (in this case, the code above would be generally inefficient for a LinkedList<T>
).
One thing to keep in mind when working with collections is IEnumerable<T>
and the possibility that it's an infinite sequence. In those cases, unless you know the concrete type of the IEnumerable<T>
or through other means know that it's finite, it's possibly best to re-think the idea of getting the "last n items", as it may not even be possible.