views:

138

answers:

4

Hello, I am porting a library from C++ to C#. The old library uses vectors from C++ and in the C# I am using generic Dictionaries because they're actually a good data structure for what I'm doing (each element has an ID, then I just use using TypeDictionary = Dictionary<String, Type>;). Now, in the C# code I use a loop like this one

TypeDictionary.Enumerator tdEnum = MyTypeDictionary.GetEnumerator();

while( tdEnum.MoveNext() ) 
{
   Type element = typeElement.Current.Value;

   // More code here
}

to iterate through the elements of the collection. The problem is that in particular cases I need to check if a certain enumerator has reached the end of the collection, in C++ I would have done a check like this:

if ( tdEnum == MyTypeDictionary.end() ) // More code here

But I just don't know how to handle this situation in C#, any ideas?

Thank you
Tommaso

+6  A: 

Here's a pretty simple way of accomplishing this.

bool hasNext = tdEnum.MoveNext();
while (hasNext) {
    int i = tdEnum.Current;
    hasNext = tdEnum.MoveNext();
}

I found an online tutorial that also may help you understand how this works.

http://www.c-sharpcorner.com/UploadFile/prasadh/Enumerators11132005232321PM/Enumerators.aspx

Robert Greiner
+3  A: 

You know that you're at the end of an iterator when MoveNext() returns false. Otherwise you need to upgrade to a more descriptive data structure like IList<T>.

Robert Davis
+3  A: 

I have a "smart iterator" class in MiscUtil which you may find useful. It lets you test whether you're currently looking at the start or end of the sequence, and the index within the sequence. See the usage page for more information.

Of course in most cases you can just get away with doing this manually using the result of MoveNext(), but occasionally the extra encapsulation comes in handy.

Note that by necessity, this iterator will always have actually consumed one more value than it's yielded, in order to know whether or not it's reached the end. In most cases that isn't an issue, but it could occasionally give some odd experiences when debugging.

Jon Skeet
Thank you for your library, I have bookmarked it, but for this time I'll just go with the quick solution. :)
tunnuz
+1  A: 

Coming from C++ you might not be up to date on C# syntax. Perhaps you could simply use the foreach construct to avoid the test all together. The following code will be executed once for each element in your dictionary:

foreach (var element in MyTypeDictionary)
{
    // More code here
}
MEMark