2009-07-21
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#ではどうする?
C#3.0から実装された拡張メソッドを使用する。
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ループ使えばいい気もするけど・・・
トラックバック - http://d.hatena.ne.jp/eo-oe-aaaa/20090721/1248158740
リンク元
- 5 http://neue.cc/2009/07/21_178.html
- 3 http://d.hatena.ne.jp/keyword/C#
- 3 http://reader.livedoor.com/reader/
- 3 http://www.google.co.jp/reader/view/
- 1 http://blogsearch.google.co.jp/blogsearch?hl=ja&client=firefox-a&um=1&ie=UTF-8&q=スコット・ガスリー&btnG=ブログ検索&lr=lang_ja
- 1 http://blogsearch.google.co.jp/blogsearch?hl=ja&ie=UTF-8&q=ruby&btnG=ブログ検索&lr=lang_ja
- 1 http://blogsearch.google.co.jp/blogsearch?hl=ja&q=C#&lr=&um=1&ie=UTF-8&sa=N&tab=wb
- 1 http://blogsearch.google.co.jp/blogsearch?hl=ja&q=ruby&sourceid=navclient-ff&rlz=1B3GGGL_jaJP335JP335&um=1&ie=UTF-8&sa=N&tab=wb
- 1 http://blogsearch.google.co.jp/blogsearch?hl=ja&um=1&scoring=d&ie=UTF-8&q=WPF&lr=lang_ja&sa=N&start=10
- 1 http://neue.cc/