Java Iterator vs C# IEnumerable
It's not used very often, but the analogy is the IEnumerator<T>
interface:
var enumerator = labels.GetEnumerator();
.NET's IEnumerator
differs from Java's Iterator
with the following:
Iterator
after construction is pointing at the first element of the collection (or, for an empty collection, is invalid andhasNext
will returnfalse
immediately),IEnumerator
points initially before the first element of the collection (for an empty collectionMoveNext
will returnfalse
)Iterator
hashasNext
method, while forIEnumerator
you verify the result ofMoveNext
methodIterator
hasnext
method, while forIEnumerator
you also useMoveNext
Iterator
'snext
returns the next element, while withIEnumerator
you useCurrent
property after callingMoveNext
Iterator
in Java hasremove
method which allows you to remove elements from the underlying collection. There is no equivalent inIEnumerator
So for Java you'd iterate with something like this:
it = labels.iterator();
while (it.hasNext())
{
elem = it.next();
}
While in C#:
en = labels.GetEnumerator();
while (en.MoveNext())
{
elem = en.Current;
}
Usually, having labels
as a collection (which always implements IEnumerable<T>
) you just use it directly:
foreach (var label in labels)
{
//...
}
And of course, you can store IEnumerable<T>
for later use (names referring to your example):
IEnumerable<Label> it = labels;
Beware, that IEnumerable<T>
is lazy, just like Iterator
in Java.
You can also easily obtain a snapshot of a collection like this (again, it
refers to your example, better name could be chosen):
IEnumerable<Label> it = labels.ToArray();
// or Label[] it = labels.ToArray();
// or better: var it = labels.ToArray();