Skip to content

Instantly share code, notes, and snippets.

@kostrse
Last active February 27, 2016 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kostrse/6784256 to your computer and use it in GitHub Desktop.
Save kostrse/6784256 to your computer and use it in GitHub Desktop.
Last N-th of IEnumerable
public static class LinkedListExtensions
{
public static T Last<T>(this IEnumerable<T> items, int index)
{
T[] keepItems = new T[index];
int position = 0;
int count = 0;
foreach (var item in items)
{
keepItems[position++] = item;
if (position == keepItems.Length)
position = 0;
count++;
}
if (count < index)
return default(T);
return keepItems[position % count];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment