Skip to content

Instantly share code, notes, and snippets.

@handcraftsman
Created April 29, 2010 17:22
Show Gist options
  • Save handcraftsman/383915 to your computer and use it in GitHub Desktop.
Save handcraftsman/383915 to your computer and use it in GitHub Desktop.
public static IEnumerable<T> AllButLast<T>(this IEnumerable<T> input)
{
var next = input.First();
foreach(var item in input.Skip(1))
{
yield return next;
next = item;
}
}
alternative that only starts the iteration once:
public static IEnumerable<T> AllButLast<T>(this IEnumerable<T> input)
{
bool haveNext = false;
var next = default(T);
foreach (var item in input)
{
if (!haveNext)
{
haveNext = true;
next = item;
continue;
}
yield return next;
next = item;
}
}
@handcraftsman
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment