コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【C#】SkipWhileLast の実装例

ソースコード

using System;
using System.Collections.Generic;

public static class EnumerableExtensionMethods
{
    public static IEnumerable<T> SkipWhileLast<T>
    (
        this IEnumerable<T> self,
        Func<T, bool>       predicate
    )
    {
        var buffer       = new List<T>();
        var yieldStarted = false;

        foreach ( var item in self )
        {
            if ( predicate( item ) )
            {
                buffer.Add( item );
                yieldStarted = true;
            }
            else
            {
                if ( yieldStarted )
                {
                    foreach ( var bufferedItem in buffer )
                    {
                        yield return bufferedItem;
                    }

                    buffer.Clear();
                }

                yield return item;
            }
        }
    }
}

使用例

using UnityEngine;

public class Example : MonoBehaviour
{
    private void Start()
    {
        var numbers = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        var result = numbers.SkipWhileLast( x => 7 <= x );

        // 1, 2, 3, 4, 5, 6 
        foreach ( var item in result )
        {
            Debug.Log( item );
        }
    }
}