C#にもほしい 〜rubyのeach_with_index〜
C#のforeachは便利なのだが、
現在処理している場所のインデックスを取得することができない。
だが、何かとインデックスが必要になることがある。
そこで、Rubyのeach_with_indexと同等の機能を持つものを作ってみる。
rubyのeach_with_index
(5..10).each_with_index do |item,i| p "item=" + item.to_s + " index=" + i.to_s end
結果
item=5 index=0 item=6 index=1 item=7 index=2 item=8 index=3 item=9 index=4 item=10 index=5
C#のEachWithIndex
public static class Extension { static public void EachWithIndex<T>(this IEnumerable<T> collection, Action<T, int> action) { int count = collection.Count(); for (int i = 0; i < count; ++i) { action(collection.ElementAt(i), i); } } } static void Main(string[] args) { new List<int>(Enumerable.Range(5, 6)).EachWithIndex((item, index) => Console.WriteLine( "item=" + item + " index=" + index ) ); }
やったね
これでインデックス操作も簡単だ。
※単純にForループ使えばいい気もするけど・・・