ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

SkipLast

take all but the last item from an IEnumerable<T>

Source

public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source)
{
	if (!source.Any())
	{
		yield break;
	}
	Queue<T> items = new Queue<T>();
	items.Enqueue(source.First());
	foreach(T item in source.Skip(1))
	{
		yield return items.Dequeue();
		items.Enqueue(item);
	}
}

Example

List<int> items = new List<int>(new[]{ 1, 2, 3, 4, 5, 6});
foreach(int item in items.SkipLast())
{
  Console.WriteLine(item);
}

gets:
1
2
3
4
5

Author: Clinton Sheppard

Submitted on: 9 jun 2009

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 3010