C#でeach_with_indexをする
Rubyのeach_with_indexって便利ですよね。
C#には、each=ForEach、map=Select、select=WhereとRubyのEnumeratorのメソッドに相当するものが有りますが、私の大好きなeach_with_index相当がありません。
ということで、拡張メソッドを使ってサクッとモンキーパッチしましょう。
static class Extensions
{
public static void EachWithIndex<TSource>(
this IEnumerable<TSource> source,
Action<TSource,int> block)
{
int i = 0;
foreach (TSource e in source)
block(e,i++);
}
}
こんな感じで使います。
new List<string> {"a","b","c"}.EachWithIndex( (x, j) => Console.WriteLine(x + j)); //=> "a0" "b1" "c2"
いやー、C#って便利。