C# - Head & Tail extension methods - without using Linq

We previously created Head() and Tail() extension methods for any collection that implements IEnumerable. We did this using Linq.

This article implements the same two functions, again as extension methods, but this time 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

Source code

using System;
using System.Collections.Generic;
 
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