tags:

views:

285

answers:

4

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 in C# or is there a better C# idiom?

+3  A: 

In .NET in general, you are going to use the IEnumerable<T> interface. This will return an IEnumerator<T> which you can call the MoveNext method and Current property on to iterate through the sequence.

In C#, the foreach keyword does all of this for you. Examples of how to use foreach can be found here:

http://msdn.microsoft.com/en-us/library/ttw7t8t6(VS.80).aspx

casperOne
+1  A: 

Yes, in C#, its called an Enumerator.

Andrew Keith
A: 

Even though this is supported by C# via IEnumerator/IEnumerable, there is a better idiom: foreach

foreach (SGroup nextSGroup in items)
{
    //...
}

for details, see MSDN: http://msdn.microsoft.com/en-us/library/aa664754%28VS.71%29.aspx

Marek
+6  A: 

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)

Lee
Strictly speaking, the "direct equivalent" code should have a `using`. Also, for the two version to be directly compatible (in edge cases) the `nextSGroup` would be declared *outside* the `while` (this makes a difference for captured variables).
Marc Gravell
@Marc Gravell - Thanks - updated example...
Lee
Shouldn't this be MoveNext() and not GetNext()?
Doron Yaacoby
@Hitchhiker - yes it should, thanks.
Lee