Last active
February 27, 2016 19:28
-
-
Save kostrse/6784256 to your computer and use it in GitHub Desktop.
Last N-th of IEnumerable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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