C# - How to get the tail of an Array

The simplest solution is to define two extension methods, Head() and Tail(), that can be called on any collection that implements IEnumerable.

The implementation for each method is just one line. Source code is provided below.

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

The complete program

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));
        }
    }
}

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath