开发者

what is the c# equivalent of Iterator in Java

开发者 https://www.devze.com 2022-12-08 14:18 出处:网络
I am manually converting Java to C# and have the following code: for (Iterator<SGroup> theSGroupIterator = SGroup.getSGroupIterator();

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

for (Iterator<SGroup> theSGroupIterator = SGroup.getSGroupIterator();
     theSGroupIterator.hasNext();)
{
    SGroup nextSGroup =开发者_StackOverflow社区 theSGroupIterator.next();
}

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


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


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


Yes, in C#, its called an Enumerator.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消