Butlast メソッド

シーケンスの最後の要素を取り除く Butlast メソッドを作ってみました。

using System;
using System.Collections.Generic;
using System.Linq;

public static class Ext {
    public static IEnumerable<T> Butlast<T>(this IEnumerable<T> xs) {
        bool first = true;
        T prev = default(T);
        foreach (var x in xs) {
            if (!first) {
                yield return prev;
            }
            prev = x;
            first = false;
        }
    }
}

class Program {
    static void Display<T>(IEnumerable<T> xs) {
        Console.WriteLine("count:{0} [{1}]", xs.Count(), string.Join(" ", xs));
    }

    static void Main() {
        Display(new[] { 1, 2, 3 }.Butlast()); // count:2 [1 2]
        Display(new[] { 1, 2 }.Butlast());    // count:1 [1]
        Display(new[] { 1 }.Butlast());       // count:0 []
        Display(Enumerable.Empty<int>().Butlast()); // count:0 []
    }
}

実行結果です。

count:2 [1 2]
count:1 [1]
count:0 []
count:0 []

参考