C# - How to get the tail of an Array - without using Linq

The simplest solution is to define two extension methods, Head() and Tail(). In a previous article, we did this using Linq.

This article provides a similar solution, again using extension methods, but without using Linq.

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 Array<T>
    public static class ArrayExtensions
    {
        public static T Head<T>(this T[] source)
        {
            if (source.Length == 0)
                throw new InvalidOperationException();
            return source[0];
        }
        public static T[] Tail<T>(this T[] source)
        {
            if (source.Length == 0)
                return new T[] { };
            var copy = new T[source.Length - 1];
            Array.Copy(source, 1, copy, 0, copy.Length);
            return copy;
        }
    }
 
    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