The example program (full source code is provided below) implements two extension methods, Head() and Tail(), that can be called on any collection that implements IEnumerable (including List and Array).
These methods are especially useful for functional style programming.
If you prefer a version that doesn't use Linq, there is a link at the bottom of the page.
var numbers = new[] { 1, 2, 3, 4, 5 };
var head = numbers.Head();
var tail = numbers.Tail();
Program output:
Head = 1
Tail = 2, 3, 4, 5
Source code
using System;
using System.Collections.Generic;
using System.Linq;
namespace Zuga.net
{
// Head & Tail Extension methods for IEnumerable<T>
public static class EnumerableExtensions
{
public static T Head<T>(this IEnumerable<T> source)
{
return source.First();
}
public static IEnumerable<T> Tail<T>(this IEnumerable<T> source)
{
return source.Skip(1);
}
}
class Program
{
static void Main(string[] args)
{
var numbers = new[] { 1, 2, 3, 4, 5 };
var head = numbers.Head();
var tail = numbers.Tail();
Console.WriteLine("Head = " + head);
Console.WriteLine("Tail = " + String.Join(", ", tail));
}
}
}