ソースコード
using System;
using System.Collections.Generic;
public static class IEnumerableExt
{
public static IEnumerable<(int index, T value)> WithIndex<T>
(
this IEnumerable<T> source
)
{
if ( source == null )
{
throw new ArgumentNullException( nameof( source ) );
}
IEnumerable<(int index, T value)> Impl()
{
var i = 0;
foreach ( var value in source )
{
yield return ( i, value );
i++;
}
}
return Impl();
}
}
使用例
通常
var index = 0;
foreach ( var value in list )
{
Debug.Log( index + ":" + value );
index++;
}
拡張メソッド
foreach ( var ( index, value ) in list.WithIndex() )
{
Debug.Log( index + ":" + value );
}