peter.murray.rust
peter.murray.rust

Reputation: 38033

what is the c# equivalent of Iterator in Java

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?

Upvotes: 19

Views: 15998

Answers (4)

Lee
Lee

Reputation: 144136

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).

Upvotes: 26

Marek
Marek

Reputation: 10402

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(VS.71).aspx

Upvotes: 1

Andrew Keith
Andrew Keith

Reputation: 7563

Yes, in C#, its called an Enumerator.

Upvotes: 1

casperOne
casperOne

Reputation: 74530

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

Upvotes: 4

Related Questions