コガネブログ

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

【C#】配列やリストで要素が末尾かどうかを判定できるループ構文の拡張メソッド

ソースコード

using System;
using System.Collections.Generic;

public static class ListExt
{
    public struct ForEachData<T>
    {
        private readonly int    m_index     ;
        private readonly T      m_value     ;
        private readonly bool   m_isLast    ;
        
        public int  Index   { get { return m_index  ; } }
        public T    Value   { get { return m_value  ; } }
        public bool IsLast  { get { return m_isLast ; } }

        public ForEachData
        (
            int     index   , 
            T       value   , 
            bool    isLast  
        )
        {
            m_index     = index     ;
            m_value     = value     ;
            m_isLast    = isLast    ;
        }
    }

    public static void ForEach<T>
    ( 
        this IList<T>          self     , 
        Action<ForEachData<T>> callback 
    )
    {
        var count = self.Count;

        for ( int i = 0; i < count; i++ )
        {
            var data = new ForEachData<T>
            (
                index   : i,
                value   : self[ i ],
                isLast  : i == count - 1
            );

            callback( data );
        }
    }
}

使い方

var list = new [] { 1, 2, 3 };

list.ForEach( data =>
{
    Console.WriteLine( "{0}: {1}", data.Value, data.IsLast );
} );

結果

1: False
2: False
3: True