Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the c# equivalent of Iterator in Java

Tags:

java

iterator

c#

I am manually converting Java to C# and have the following code:

for (Iterator<SGroup> theSGroupIterator = SGroup.getSGroupIterator();
     theSGroupIterator.hasNext();)
{
    SGroup nextSGroup = theSGroupIterator.next();
}

Is there an equivalent of Iterator<T> in C# or is there a better C# idiom?

like image 418
peter.murray.rust Avatar asked Oct 17 '09 09:10

peter.murray.rust


1 Answers

The direct equivalent in C# would be IEnumerator<T> and the code would look something like this:

SGroup nextSGroup;
using(IEnumerator<SGroup> enumerator = SGroup.GetSGroupEnumerator())
{
    while(enumerator.MoveNext())
    {
        nextSGroup = enumerator.Current;
    }
}

However the idiomatic way would be:

foreach(SGroup group in SGroup.GetSGroupIterator())
{
    ...
}

and have GetSGroupIterator return an IEnumerable<T> (and probably rename it to GetSGroups() or similar).

like image 194
Lee Avatar answered Oct 22 '22 09:10

Lee