LinkedList<string> list = .... ;
foreach ( string item in list ) {
.... えーと、今何番目?
}
…ってこと、ありますよね。仕方ないから:
int i = 0;
foreach ( string item in list ) {
... i番目処理ちゅー♪
++i;
}
なんかかっこイクないので、こんなの作ってみた:
ForEachAudit<string> audit = new ForEachAudit<string>();
foreach ( string item in audit.Start(list) ) {
... audit.Count 番目処理ちゅー♪
}
つまりこの、ForEachAudit<T>.Count がforeach-loopと連動します。
using System.Collections;
using System.Collections.Generic;
namespace Wankuma.Collections.Generic {
class ForEachAuditEnumerator<T> : IEnumerator<T> {
private IEnumerator<T> enumerator_;
private ForEachAudit<T> audit_;
public ForEachAuditEnumerator(IEnumerator<T> enumerator, ForEachAudit<T> audit)
{ enumerator_ = enumerator; audit_ = audit; audit_.Reset(); }
public T Current { get { return enumerator_.Current; } }
object IEnumerator.Current { get { return enumerator_.Current; } }
public bool MoveNext() { audit_.MoveNext(); return enumerator_.MoveNext(); }
public void Reset() { audit_.Reset(); enumerator_.Reset(); }
public void Dispose() { enumerator_.Dispose(); }
}
public class ForEachAudit<T> : IEnumerable<T> {
private IEnumerable<T> enumerable_;
private int count_;
public IEnumerator<T> GetEnumerator()
{ return new ForEachAuditEnumerator<T>(enumerable_.GetEnumerator(),this); }
IEnumerator IEnumerable.GetEnumerator()
{ return new ForEachAuditEnumerator<T>(enumerable_.GetEnumerator(), this); }
public IEnumerable<T> Start(IEnumerable<T> enumerable)
{ enumerable_ = enumerable; return this; }
public int Count { get { return count_; } }
public void Reset() { count_ = -1; }
public bool MoveNext() { ++count_; return true; }
}
class Program {
static void Main() {
string[] array = { "zero", "one", "two", "three" };
ForEachAudit<string> audit = new ForEachAudit<string>();
foreach ( string value in audit.Start(array) ) {
System.Console.WriteLine("{0} {1}", audit.Count, value);
}
}
}
}